Node + Express Session Expiration?

Viewed 49347

I have an app in express and I have a login form. I need sessions to last for 1 month do I set maxAge to a month in milliseconds.

I left two computers on and logged in for 24 hours and when I came back both were logged out.

How do I fix this/achieve what I'm trying to do? Thanks.

5 Answers

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