25

I have an Express 4 app setup to have sessions.

// Sessions
app.use(cookieParser());
app.use(session({ secret: "some-secret" }));

// Signup
app.post("/signup", function (req, res) {
    create_user(req.body.user, function (err, user_id) {
        req.session.user_id = user_id;
        res.redirect("/admin");
    });
});

When I submit the form, it saves the user_id to the req.session. However, when I restart the server, the session is gone.

Why isn't it persisting? Am I missing some configuration?

eldosoa
  • 295
  • 1
  • 4
  • 9

2 Answers2

55

The default session store for express-session is MemoryStore, which as the name suggests, stores sessions in memory only. If you need persistence, there are many session stores available for Express. Some examples:

For a updated and more complete list visit Compatible Session Stores.

Serg
  • 2,346
  • 3
  • 29
  • 38
mscdex
  • 104,356
  • 15
  • 192
  • 153
  • Cookie-session seems like it can be used as a replacement to express-session whereas for the rest, they are to be used along with express-session. How correct is the above understanding? – Adarsh Rao Mar 10 '21 at 07:45
1

@mscdex answer is great but in case you are looking for code samples. Here is one with connect-mongo which should work fine if you mongodb and mongoose.

Install the package:

npm i connect-mongo

require the package:

const session = require('express-session'); // You must have express-sessions installed
const MongoStore = require('connect-mongo')(session)

Now configure the session:

app.use(
  session({
    secret: "mysecrets",
    resave: false,
    saveUninitialized: false,
    store: new MongoStore({ 
      mongooseConnection: mongoose.connection,
      ttl: 14 * 24 * 60 * 60
     }),

  })
);

Again this assumes you are using mongoose and have the connection configured.

If you did everything right, it should work just fine.

Paschal
  • 725
  • 1
  • 9
  • 17