Race condition when using req.session.save() in trying to redirect
See original GitHub issueI’m experiencing issue #74 that was closed. There are also similar issues reported in stackoverflow.
Problem: Race condition when using req.session.save()
Explanation:
...
router.get('/logout', function(req, res, next){
req.logout();
res.redirect('/')
});
...
I’m trying to do a successful logout. I first call req.logout()
to update the req.session
and then I call res.redirect('/')
to have express-session update the session to a file. I’m using the store session-file-store. The problem lies when res.redirect('/'
calls res.end()
inside the ./express-session/indes.js
res.end(){
...
if (shouldSave(req)) {
req.session.save(function onsave(err) {
if (err) {
defer(next, err);
}
writeend();
});
return writetop();
} else if (storeImplementsTouch && shouldTouch(req)) {
...
req.session.save
gets run asynchronously, which then immediately the redirects happens which loads a session, but the req.session.save
hasn’t finished yet updating the file! which then the old state of the session gets loaded and then the req.session.save
finishes, but its too late:(
...
"express": "4.16.2"
"express-session": "1.15.6"
"session-file-store": "1.1.2"
...
app.use(session({
store: new FileStore(),
secret: 'keyboard mouse',
resave: false,
saveUninitialized: false
}));
...
I hope this makes sense. I tried the workaround offered in #74 to call res.session.save
before the redirect BUT then I end up calling the res.session.save twice! which #74 supposedly should have fixed it.
Other similar issues #309
Issue Analytics
- State:
- Created 6 years ago
- Comments:5 (3 by maintainers)
Top GitHub Comments
Yea, I would like to fix it, but not certain how. Any thoughts on it would be much appreciated!
Seems there are two options for a fix after experimenting and reading different github issues:
req.session.save(err => _<handle error or res.redirect>_)
Saved session data should be available by the time the callback is calledOption 1 seems to work for me and be less kludgy. I did spend a couple hours scratching my head though why it stopped working in a modified environment. Turns out I was serving my Express app locally without SSL but had this set on my session store’s options param:
sessionOptions.cookie.secure = true
. That was enough to prevent my custom session data from persisting in the session but I got no errors in the console. I suppose if one were to create a PR around this it would be to compare the request protocol with the session storesecure
option. I don’t think I’ll have time to do it, sorry.Leaving this here in case it helps someone.
Thanks for the library, it’s actually really great!