Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 307
Stephen Avatar asked Apr 06 '11 21:04

Stephen


People also ask

How do I destroy a session in Express?

destroy session value in Express: Node.jsOnce the user clicks on /logout we destroy all the session by using req. session.

How do Sessions work in Express?

How sessions works. When the client makes a login request to the server, the server will create a session and store it on the server-side. When the server responds to the client, it sends a cookie. This cookie will contain the session's unique id stored on the server, which will now be stored on the client.

How do I set up an Express session?

In the following example, we will create a view counter for a client. var express = require('express'); var cookieParser = require('cookie-parser'); var session = require('express-session'); var app = express(); app. use(cookieParser()); app. use(session({secret: "Shh, its a secret!"})); app.

Is ExpressJS back end?

js, or simply Express, is a back end web application framework for Node. js, released as free and open-source software under the MIT License. It is designed for building web applications and APIs.


2 Answers

Express 4.x Updated Answer

Session handling is no longer built into Express. This answer refers to the standard session module: https://github.com/expressjs/session

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.)

like image 181
Brad Avatar answered Sep 28 '22 21:09

Brad


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

like image 23
Stephen Avatar answered Sep 28 '22 21:09

Stephen