Updating cookie session in express not registering with browser Updating cookie session in express not registering with browser express express

Updating cookie session in express not registering with browser


Express-session supports a rolling cookie expiration date. Unfortunately, it was only recently documented.

Use the "rolling" option for your session. This "forces a cookie set on every response" and "resets the expiration date." You want to set rolling to true.

Also pay attention to the "resave" option. That "forces session to be saved even when unmodified..." You'll likely want to set that option to true as well. Note that even though the default value is true for this option, you should set the value explicitly. Relying on the default for this option, rather than setting it explicitly, is now deprecated.

Try something like:

app.use( session( { secret: 'keyboard cat',                    cookie: { maxAge: 60000 },                    rolling: true,                    resave: true,                     saveUninitialized: false                  }         ));

Here's the documentation. Look under "Options" and "options.resave": https://github.com/expressjs/session .


After some digging it turns out Express does not support this sort of rolling, and is left as an exercise for the programmer to implement.

It would help if the browsers expirary was reliably readable to express, so you could bump the session only when it's close to expirary, but I use this as a workaround (inefficient) until I figure something smarter out:

check_auth = function(req, res, next) {  console.log(req.isAuthenticated());  if (req.isAuthenticated()) {    if (req.session.roll) {      req.session.roll = 0;    } else {      req.session.roll = 1;    }    return next();  }  return res.redirect('/login');};

Where roll could be anything, the point being the session is changed (on every auth-checked request*).

*) which also means it's wildly inefficient, but it will do for now.

One alternative could be to lookup the TTL of the session id. This would have to be checked in a way like:if ttl < 10% * maxAge (as defined by the app), as the TTL is actually correctly updated on every request, it's just that Set-Cookie isn't sent. As such, say the user stays within the 90% of maxAge, his browser-cookie will eventually expire, so even that approach is not sufficient. It could be a good middleground though.

I'll leave the question unaccepted, to encourage others to weigh in with better solutions.


just in case someone is facing this issue in Google Chrome, the solution is very easy:

app.use(cors({   allowedHeaders: ['Content-Type','Authorization'],   origin: '.dev.loc', <- your domain here, but it requires to have a dot infront   methods:['GET','POST','PUT','DELETE'],   preflightContinue: true}));