Node + Express Session Expiration?

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.


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
    }
  })
);