Why is PassportJS in Node not removing session on logout Why is PassportJS in Node not removing session on logout express express

Why is PassportJS in Node not removing session on logout


Brice’s answer is great, but I still noticed an important distinction to make; the Passport guide suggests using .logout() (also aliased as .logOut()) as such:

app.get('/logout', function(req, res){  req.logout();  res.redirect('/'); //Can fire before session is destroyed?});

But as mentioned above, this is unreliable. I found it behaved as expected when implementing Brice’s suggestion like this:

app.get('/logout', function (req, res){  req.session.destroy(function (err) {    res.redirect('/'); //Inside a callback… bulletproof!  });});

Hope this helps!


Ran into the same issue. Using req.session.destroy(); instead of req.logout(); works, but I don't know if this is the best practice.


session.destroy may be insufficient, to make sure the user is fully logged out you have to clear session cookie as well.

The issue here is that if your application is also used as an API for a single page app (not recommended but quite common) then there can be some request(s) being processed by express that started before logout and end after logout. If this were the case then this longer running request will restore the session in redis after it was deleted. And because the browser still has the same cookie the next time you open the page you will be successfully logged in.

req.session.destroy(function() {    res.clearCookie('connect.sid');    res.redirect('/');});

That's the what maybe happening otherwise:

  1. Req 1 (any request) is received
  2. Req 1 loads session from redis to memory
  3. Logout req received
  4. Logout req loads session
  5. Logout req destroys session
  6. Logout req sends redirect to the browser (cookie is not removed)
  7. Req 1 completes processing
  8. Req 1 saves the session from memory to redis
  9. User opens the page without login dialog because both the cookie and the session are in place

Ideally you need to use token authentication for api calls and only use sessions in web app that only loads pages, but even if your web app is only used to obtain api tokens this race condition is still possible.