4

I use express.session with connect-mongo to store user sessions. I set cookie maxAge to 2 weeks from now, but what I want is that if the user is active within those 2 weeks, the session extends to another 2 weeks, so that when he is inactive for 2 weeks his session gets deleted (both the cookie and the session in mongo). But the problem is that the session gets updated in MongoDB when he visits a page, but the cookie will expire in 2 weeks and won't change it's 'expires'. This is my code:

app.use(express.session({
  secret: 'superSecretKey',
  cookie: {maxAge: 3600000*24*14},
  store: new MongoStore({
    mongoose_connection: mongoose.connections[0],
    db: 'myDb'
  })
}));

How can I achieve what I want? Thanks!

Ivan
  • 1,801
  • 2
  • 23
  • 40
  • 1
    See [this answer](http://stackoverflow.com/a/14529888/893780) on how to achieve that. Apart from that, `maxAge` should be set to a number of milliseconds in the future at which the session will expire, and not a date (that's what `expires` is for). So use this: `maxAge : 3600000*24*14` to set the expiry to two weeks. – robertklep Oct 09 '13 at 18:01
  • Thanks! I also found this on https://github.com/senchalabs/connect/issues/670. And yeah, I always mix up expires and maxAge, I edited the question and posted an answer – Ivan Oct 09 '13 at 18:11

1 Answers1

3

I finally solved it, you have to use a middleware to update any data in the session so that the cookie gets resend, just like this:

app.use(function(req, res, next) {
  req.session._garbage = Date();
  req.session.touch();
  next();
});

This way maxAge will update both on the cookie and on the session on every request to the app.

Ivan
  • 1,801
  • 2
  • 23
  • 40
  • I want to do a similar thing, but for say 2 hours. Do I simply set the `maxAge` as in your original question and then put this `app.use` in the config ? – avrono Apr 07 '14 at 16:39
  • req.session.regenerate(callback) does not work for you ? – Leonardo May 10 '14 at 02:39