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("https://stackoverflow.com/"); //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("https://stackoverflow.com/"); //Inside a callback… bulletproof!
  });
});

Hope this helps!

Leave a Comment