How to keep alive an NodeJS Passport session

Viewed 9995

We're Node + Express + Passport for authentication, and persisting the session info to Redis. I have maxAge set on the session cookie, to time out in one hour. That all seems to be working fine but the problem is, the session cookie will expire in one hour regardless of the user's activity.

Is there a way I can manually refresh/keep alive the session cookie?

4 Answers

Yes you can! If the cookie is unchanged on a request then it will not be resent to the browser, you can check in the developer tools under cookies to verify that. So what some, including myself like to do is to change the cookie on request where there is user activity that should extend the session. Something like the following:

req.session.lastAccess = new Date().getTime();

Another thing I've seen but I've had trouble with is to use the Session#touch:

req.session.touch()

Yes, you can manually reset the maxAge for each cookie after the user logs in:

req.session.cookie.maxAge = 60 * 60 * 1000;

Here is the connect session documentation.

Try this code:

app.use(session({ secret: 'Category', cookie: { maxAge: 6000000 }, resave: true, saveUninitialized: false}));

Related