I am having trouble getting my system to log out with PassportJS. It seems the logout route is being called, but its not removing the session. I want it to return 401, if th
All examples here do a redirect after the req.session.destroy. But do realise that Express will create a new session instantly for the page you are redirecting to. In combination with Postman I found the strange behaviour that doing a Passport-Login right after the logout gives the effect that Passport is successful but cannot store the user id to the session file. The reason is that Postman needs to update the cookie in all requests for this group, and this takes a while. Also the redirect in the callback of the destroy does not help.
I solved it by not doing a redirect but just returning a json message.
This is still an issue.
What I did was to use req.session.destroy(function (err) {});
on the server side and on the client side, whenever they logout:
const logout = () => {
const url = '/users/logout'
fetch(url)
setTimeout(function () {
location.reload(); }, 500);
That way, when refreshing the page, the user is without session. Just make sure you are redirecting to the correct page if no one is authenticated.
Not the best approach, perhaps, but it works.
I was recently having this same issue and none of the answers fixed the issue for me. Could be wrong but it does seem to have to do with a race condition.
Changing the session details to the options below seems to have fixed the issue for me. I have tested it about 10 times or so now and everything seems to be working correctly.
app.use(session({
secret: 'secret',
saveUninitialized: false,
resave: false
}));
Basically I just changed saveUninitialized
and resave
from true
to false
. That seems to have fixed the issue.
Just for reference I'm using the standard req.logout();
method in my logout path. I'm not using the session destroy like other people have mentioned.
app.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
I used both req.logout()
and req.session.destroy()
and works fine.
server.get('/logout', (req, res) => {
req.logout();
req.session.destroy();
res.redirect('/');
});
Just to mention, i use Redis as session store.
I was having the same issues, capital O fixed it;
app.get('/logout', function (req, res){
req.logOut() // <-- not req.logout();
res.redirect('/')
});
Edit: this is no longer an issue.
You shoulde be using req.logout() to destroy the session in the browser.
app.get('/logout', function(req, res) {
req.logout();
res.redirect('/'); // whatever the route to your default page is
});