Node + Express Session Expiration? Node + Express Session Expiration? express express

Node + Express Session Expiration?


The accepted answer by @Vadim Baryshev is flawed in at least the most recent express-session implementations. When your app starts up you create the session implementation and set the max age. As for the answer using expires, that is not recommended, stick with maxAge.

This means that the maxAge example as written would expire every single session a month after the server starts, and every session created in the future would be expired immediately. Until the server was restarted, there would not be any valid sessions.

Instead of passing a date object, just pass the number of milliseconds to the maxAge property like so:

app.use(  session({    ...,    cookie: {      maxAge: 30 * 24 * 60 * 60 * 1000    }  }));


You can use expires attribute instead of maxAge. It takes Date object as value. Also, check session cookie exipres on client after they set. Maybe session ended by server (i.e. memcached restart).

Code example:

app.use(express.session(  { secret: "secret", store: new MemoryStore(), expires: new Date(Date.now() + (30 * 86400 * 1000))   }));

but

  app.use(express.session(    { secret: "secret", store: new MemoryStore(), maxAge: Date.now() + (30 * 86400 * 1000)     }));

works fine for me too.


maxAge means how long the session lasts, in ms;expires means when the session gonna expire, ie: a date object

var hour = 3600000req.session.cookie.expires = new Date(Date.now() + hour)

or

var hour = 3600000req.session.cookie.maxAge = hour

Documentation