How to End a Session in Expressjs

How to End a Session in Expressjs

I feel like this has to be buried somewhere in the documentation, but I can't find it.

How do you close or end or kill (whatever) a session in ExpressJS?

1

10 Answers

Express 4.x Updated Answer

Session handling is no longer built into Express. This answer refers to the standard session module:

To clear the session data, simply use:

req.session.destroy();

The documentation is a bit useless on this. It says:

Destroys the session, removing req.session, will be re-generated next request. req.session.destroy(function(err) { // cannot access session here })

This does not mean that the current session will be re-loaded on the next request. It means that a clean empty session will be created in your session store on next request. (Presumably the session ID isn't changing, but I have not tested that.)

2

Never mind, it's req.session.destroy();

4

The question didn't clarify what type of session store was being used. Both answers seem to be correct.

For cookie based sessions:

From

req.session = null // Deletes the cookie.

For Redis, etc based sessions:

req.session.destroy // Deletes the session in the database.
1

From

To clear a cookie simply assign the session to null before responding:

req.session = null
0
Elena Rostova
Author

Elena Rostova

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.