4
votes

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!

1
See this answer 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
Thanks! I also found this on github.com/senchalabs/connect/issues/670. And yeah, I always mix up expires and maxAge, I edited the question and posted an answer - Ivan

1 Answers

3
votes

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.