Renewing/Refreshing Express Session Renewing/Refreshing Express Session express express

Renewing/Refreshing Express Session


You can try define your session as follows

app.use (   session ({      secret: "secret",      saveUninitialized: true,      resave: true,      cookie: {         expires: 20 * 1000      }   }));

and then refresh the session using

req.session.touch()

or you could define your session as

app.use (   session ({      secret: "secret",      saveUninitialized: false,      resave: true,      rolling: true,      cookie: {         expires: 20 * 1000      }   }));

and it will renew the session automatically and it will only expire when it has been idle for the value in the expires variable


express-session supports a duration-based maxAge setting, which will work better than setting a fixed date for all sessions. So your middleware usage should instead look like:

app.use(session({  secret: 'secret',  saveUninitialized: true,  resave: true,  maxAge: 20000}));

Next, to update the expiration of the session, you can just call req.session.touch(); if that is all you're doing to the session and its contents.

The documentation has a lot of other good information on controlling session expiration and related topics.