What we are buiding

To demonstrate Session handling in Node, I have developed a basic Log-in and log-out System. In this User can log-in by providing their email, and that email will be used for further Session tracking. Once User log-out, Session will be destroyed and User will be redirected to home page.

Creating Node Project

Let’s create a new Node project. Create a new folder and switch to it using the terminal.

Run this command to create a new Node project.

npm init --y

This command will create a new package.json file. Let’s install the required dependency.

npm install --save express express-session body-parser

Once the dependencies are installed, we can proceed to code our app.

How to use Express Session ?

Before heading to actual code, i want to put few words about express-session module. to use this module, you must have to include express in your project. Like for all packages, we have to first include it.

After this, we have to initialize the session and we can do this by using following.

app.use(session({secret: 'ssshhhhh'}));

Here ‘secret‘ is used for cookie handling etc but we have to put some secret for managing Session in Express.

Now using ‘request‘ variable you can assign session to any variable. Just like we do in PHP using $_SESSION variable. for e.g

var sess;
app.get('/',function(req,res){
sess=req.session;/*
* Here we have assign the 'session' to 'sess'.
* Now we can create any number of session variable we want.
* in PHP we do as $_SESSION['var name'].
* Here we do like this.
*/
sess.email;// equivalent to $_SESSION['email'] in PHP.
sess.username;// equivalent to $_SESSION['username'] in PHP.});

After creating Session variables like sess.email , we can check whether this variable is set or not in other routers and can track the Session easily.

Tracking session in global variable won’t work with multiple users. This is just for the demonstration.

Project Structure

We are going to put all of Server side code in the server.js file. Front-end code will be placed inside the views folder.

In jQuery code, we are calling our Router ‘/login’ and redirecting it to the ‘admin‘ if log-in is successful, you can add validation to fields as per your requirement, for demo purpose i have not added any.

The Bug Alert!

As I have mentioned earlier, using a global variable for the session won’t work for multiple users. You will receive the same session information for all of the users.

So how do we solve this? By using a session store.

We save every session in the store so that one session will belong to the one user only. I have explained and build session store using Redis in this article.

For the quick reference, he is how we can extend the code shown above using Redis as a session store.

First, you need to install Redis on your computer. Click here to learn how to install Redis.

How to run example code

Download code and extract the zip file. Open your command prompt or Terminal and switch to the directory. Install dependency first by using.

npm install

Then run code using

node server.js

Visit localhost:3000 to view the app.

Conclusion:

Like I mentioned session is very important for any web application. Node.js allows us to create an HTTP server and HTTP is a stateless protocol. It stores no information about previous visit and Express solves this problem very beautifully.

85 Comments

Hi man !
Thanks for this great post ! I’ve got an issue with session managing, if you got some minuts could you help me please ?
I written some routes with app.get(). I’ve done an app.post for the login, and the mechanism works well (I’m going to auth my user by searching into a mongodb database). I then store his username in sess.username.
But when the user then navigate to the other routes, and I check sess.username it’s always null.

I’ve written sess = req.session; in the top of every routes dedicated code and then I checked the sess.username.

Oh, and sess is a global variable.
Do you see what is messing up ? Thanks in advance 🙂

Thanks for replying Shahid 🙂
This value is true by default but I tried anyway to affect true to the resave option in session. I also tried to do a session.save function at login.
Maybe in the new version of express-session it is impossible to bind a value to the session objet ? thus i didn’t noticed something like this into the express-session doc …

Alex, I realize this was a while back, but I’ll reply in hopes that it resolves someone stuck on a similiar problem. The reason your global variable sess is null is because its being reassigned for each request after it was initially set. The purpose of binding the session to the req variable is because its the only response-specific state being passed between the express middleware and routing.

To handle concurrent session , you need to create unique Session ID and give it to client once the session is set so that next time until they logout / close browser they need to pass that unique ID in every request they made to server and you need to check it in every router.

Hi Shahid,
I am implementing the session handling for the first time. I am using NodeJs & express and Extjs for server and client side implementation respectively. The above reply of yours help me a lot. Thanks for that! However, I am struggling to send the sessionID fro client (ExtJs) back to server. Can you suggest me a way to do this? Also, if i am able to send that session ID somehow, What should i compare it with? req.sessionID?

If you want to send Anything to Nodejs server, you can do it using GET or POST HTTP method. Now as per your concern i am not sure why you want to send Session ID which you got from back-end to front-end again ?

Even I thought it was not needed to send the ID back to server and implemented it that way. But this reply of yours to “Arjun’s” query some days back, confused me slightly.

“To handle concurrent session , you need to create unique Session ID and give it to client once the session is set so that next time until they logout / close browser they need to pass that unique ID in every request they made to server and you need to check it in every router”

I am sorry if I asked something very obvious but as i have told u I am implementing this for the first time and so i want to make sure concurrent sessions are handled.

Hey Shahid, I see where my problem is! I am not using php but express.js as my api. I am all new with angular but your tuts are amazing. I actually am doing a freelance project just from stuff I learned from you!

How will your setup work among multiple node applications? I’m assuming since you haven’t configured any shared storage (such as Redis or similar) for your session, that the default memory store is used. If that’s the case – and requests are handled by different applications (running on different processes) or perhaps (if on AWS) by different EC2 instances – then none of the above will work.

Yeah you are right. Above code was for handling session in simple web application. For shared instance we need storage like Redis or something to store session key. Will write tutorial on that. Thanks.

Nice tutorial !
Can you please update to manage more then one user login at the same time .When ever a new request comes the old session data is replace by the new request .
code example
app.post(‘/validate’,function(req,res){
sess=req.session;
sess.username=req.body.username});

I have implemented passportjs for user authentication and authorization , I want to get the user details stored in session in angularjs(html not jade) frontend ?I don know how to move further Could you pls help me out ? I can see the browser cookie having the session userid but im not able to print the session details in index.js where I do my routing

I got the express session username in html without templating engine 🙂 Thank you so much for suggesting ejs. Now my issue is when i click logout btn the passport/express session isnt destroyed ,redirection to home doesn work and i also want to remove the username from the html.. im quite unclear abt logout routing whether im doing the right way or not . Your emailID pls !!

m trying to render a web page designed in polymer but unfortunately its is unable to inherit any of its data from polymer script if use normal express server . But i tried to do that with python it works good on that, can you please help me out to sort this issue. How can i run a normal polymer designed static page on Node sever other wise how to use Http server (in python : python -m http.server)

Hi shahid, I tried your tutorial, i have app.js as my main file. I want to write the rest of the code in another file in controllers. But when i try to run it, it gives me an error “cannot read property of undefined”. Please help me out

Hi shahid,iam new to nodejs.I tried this tutorial it is working well but my problem is i made my own html page and i styled it with css,now i placed my stylesheet also in views folder and i gave that path in my html page but when i visit localhost:3000 only the plain html page is displaying,css is not supporting.so how can i display the page along with css.Please help me out.

Please help in maintaining the same session id throughout the session for a single user.
When I declared session id as global, same session id is retrieved for different users. How can this happen?
How to solve the problem?

_http_outgoing.js:356
throw new Error(‘Can\’t set headers after they are sent.’);
^

Error: Can’t set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)
at ServerResponse.header (/home/julez/Workspace/js/topzeluj/node_modules/express/lib/response.js:767:10)
at ServerResponse.send (/home/julez/Workspace/js/topzeluj/node_modules/express/lib/response.js:170:12)
at done (/home/julez/Workspace/js/topzeluj/node_modules/express/lib/response.js:1004:10)
at load (/home/julez/Workspace/js/topzeluj/node_modules/twig/twig.js:7713:18)
at loadTemplateFn (/home/julez/Workspace/js/topzeluj/node_modules/twig/twig.js:5726:18)
at tryToString (fs.js:457:3)
at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:444:12)