Setting Node.js Express session expiration time in SessionStore in stead of in cookie

Redsandro picture Redsandro · Mar 12, 2014 · Viewed 34.7k times · Source

Everything I can find on Express Sessions expiring times is about setting the cookie.

session.cookie.expires = null; // Browser session cookie  
session.cookie.expires = 7 * 24 * 3600 * 1000; // Week long cookie

But the expire date of cookies is not 'secured' with your secret, as these are just cookie settings your browser manages.

How can I set the expire date of the session in the session store? Because theoretically, when someone uses your computer, they can 'fix' the expiration time of an expired cookie and continue the session, if the server side session isn't also expired at the same time as the cookie.

I can't find anything about how this works or how to set/change this.

Answer

bnuhero picture bnuhero · Mar 13, 2014

With the Session middleware, only the encrypted session ID is stored in the client side cookie. The expired date is stored as req.session.cookie.expires in the server side store. So we can add a custom middle to check whether current session is expired.

// ...
app.use(express.cookieParser());
app.use(express.session({secret:'yoursecret', cookie:{maxAge:6000}}));

app.use(function(req, res, next) {
  // if now() is after `req.session.cookie.expires`
  //   regenerate the session
  next();
});

// ...