Jonathon Oates
Jonathon Oates

Reputation: 2952

In Express the Session Cookie Expires Too Early

I may just not understand exactly how Express manages sessions, but when I set the session to expire in 7 days e.g.

app.configure(function () {
  app.set(express.static(__dirname + '/public'));
  app.use(express.bodyParser());
  app.use(express.cookieParser());
  app.use(express.session({
    expires: new Date(Date.now() + (60 * 60 * 24 * 7 * 1000)),
    secret: ''
  }));
});

The cookie is set to expire when the browsing session ends as opposed to the 7 days specified.

If I change the above code e.g.

app.configure(function () {
  app.set(express.static(__dirname + '/public'));
  app.use(express.bodyParser());
  app.use(express.cookieParser());
  app.use(express.session({
    cookie: {
      expires: new Date(Date.now() + (60 * 60 * 24 * 7 * 1000)),
    },
    secret: ''
  }));
});

The cookie is set to expire in 7 days correctly; does this also expire the session on the server too in 7 days time? I would have thought the two were coupled by default.

For bonus points; in production the sessions will be stored in Redis or similar, but during developing I am storing them in memory. Is there a way I can see this data to verify when it is set to expire too?

For even more points! The sessions are not 'rolling' by default I believe? I have read that req.session.touch() will reset the session; does this reset the session cookie's TTL too? If not, how would you suggest I 'roll' the sessions e.g.

The session is initially set to 7 days. On day 3 the user returns and the session expiration is reset to 7 days from this visit. Etc.

So the user could have a perpetual session, so long as they were active once in any rolling 7 days.

As always, help is much appreciated!

Upvotes: 1

Views: 2462

Answers (1)

damphat
damphat

Reputation: 18956

MemoryStore is the default, it is very simple, and it do not support for TTL.

source code

If you want to access to MemoryStore, just do it like this:

var ms = new MemoryStore();
app.use(express.session({
   store: ms
   ...
}))'

ms.all(function (err, array_of_session) { 
   console.log(array_of_session);
});

You should use redis or mongo to store session. For example connect-mongo, it support TTL and replica set. https://github.com/kcbanner/connect-mongo

Session rolling? No, you can do it yourself

read this https://github.com/senchalabs/connect/issues/670

Upvotes: 1

Related Questions