Search code examples
node.jsexpress-session

NodeJS cookie expiration despite resave


Is it possible to set have a maxAge for express-session cookies, and a maxAge in which the user can resave the cookie? For example I have the following settings:

app.use(session({
    secret: process.env.SECRET,
    saveUninitialized: false,
    resave: true,
    store: mongoDBStore,
    cookie: {
        maxAge: 12 * 60 * 60 * 1000
    }
}));

By this, the user has 12 hours to refresh his session. But if I'm not wrong, he can refresh his session endless. So is it possible to force a new login after for example 7 days?


Solution

  • express-session should assist you in doing this automatically. Check out the rolling property. It's set to false by default, which is what you want.

    If you absolutely positively must have a session expire at a certain time, when you first make a session you can set that expiration time, then when it elapses you can destroy the session. Something like this middleware (pseudocode) might do the trick. Put it after you use the express-session middleware. Here it's a 3_600_000 milisecond, one hour, duration.

    app.use ( (req, res, next) => {
        const now = Date.now()
        if (!req.session.expiresAt) req.session.expiresAt = now + 3_600_000
        if (now >= req.session.expiresAt) {
          req.session.unset = 'destroy'
          next(createError(403, 'your session has expired. Please log in again.'))
        } else {
          next()
        }
    } )
    

    This should remove the session when the current request is complete. Even if it doesn't remove the browser cookie, the session id won't be valid upon the next request.

    You need the http-errors package for createError().