question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Race condition when using req.session.save() in trying to redirect

See original GitHub issue

I’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:closed
  • Created 6 years ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

3reactions
dougwilsoncommented, Mar 1, 2018

Yea, I would like to fix it, but not certain how. Any thoughts on it would be much appreciated!

0reactions
abcd-cacommented, Sep 22, 2022

Seems there are two options for a fix after experimenting and reading different github issues:

  1. req.session.save(err => _<handle error or res.redirect>_) Saved session data should be available by the time the callback is called
  2. Get the front-end to do the redirect
    res.set('Content-Type', 'text/html')
    res.send(
        Buffer.from(
             '<html lang="en"><head><meta http-equiv="refresh" content="0; url=/dashboard"><title>Insightfull</title></head><body>Loading...</body></html>'
        )
    )

Option 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 store secure 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!

Read more comments on GitHub >

github_iconTop Results From Across the Web

Express-session not persistent after redirect
In this aim, I use the middleware Express-Session, but I have a problem. When the user types good credentials, its informations are correctly ......
Read more >
Express session middleware
Forces a session that is “uninitialized” to be saved to the store. A session is uninitialized when it is new but not modified....
Read more >
Java Session Flash - 2.8.x
It's important to understand that Session and Flash data are not stored in the server but are added to each subsequent HTTP Request,...
Read more >
⚓ T299193 MediaWiki login failure due to race condition ...
The session ID is reset (ie. session data is moved to a new address) on certain changes, to prevent session fixation attacks. This...
Read more >
session_start - Manual
A common workaround to this is call session_start() and session_write_close() each time you want to update the session. The problem with this, is...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found