As mentioned in several places, I'm also not able to get the req.session.destroy() function to work correctly.
This is my work around .. seems to do the trick, and still allows req.flash to be used
req.session = {};
If you delete or set req.session = null; , seems then you can't use req.flash
use,
delete req.session.yoursessionname;
Using req.session = null;
, won't actually delete the session instance. The most proper solution would be req.session.destroy();
,
but this is essentially a wrapper for delete req.session;
.
https://github.com/expressjs/session/blob/master/session/session.js
Session.prototype.destroy = function(fn){
delete this.req.session;
this.req.sessionStore.destroy(this.id, fn);
return this;
};
Destroys the session and will unset the req.session property. Once complete, the callback will be invoked.
↓ Secure way ↓ ?
req.session.destroy((err) => {
res.redirect('/') // will always fire after session is destroyed
})
↓ Unsecure way ↓ ?
req.logout();
res.redirect('/') // can be called before logout is done
req.session.destroy();
The above did not work for me so I did this.
req.session.cookie.expires = new Date().getTime();
By setting the expiration of the cookie to the current time, the session expired on its own.
The question didn't clarify what type of session store was being used. Both answers seem to be correct.
For cookie based sessions:
From http://expressjs.com/api.html#cookieSession
req.session = null // Deletes the cookie.
For Redis, etc based sessions:
req.session.destroy // Deletes the session in the database.
From http://expressjs.com/api.html#cookieSession
To clear a cookie simply assign the session to null before responding:
req.session = null
Never mind, it's req.session.destroy();
Source: Stackoverflow.com