Sessions In Express: Node.js

After learning about cookies, lets look briefly about sessions in Express applications.

sessions-express-nodejs

If you’ve ever worked on any serious web application, you already know the importance of session. Creating session for logged in users, tracking the shopping cart items, storing the URL for redirect etc are some of the basic uses of sessions.

session middleware in Express: Node.js
app.js

1
2
3
4
5
6
var express = require('express');
 
var app = express();
 
app.use(express.cookieParser());
app.use(express.session({secret: 'some secret key'}));

session middleware needs cookieParser() because session objects lookup for the cookie for matching up the requests.

setting session variable in Express: Node.js
app.js

1
2
3
4
app.get('/user/:user', function(req, res){
req.session.name = req.params.user;
res.send('<p>Session Set: <a href="/user">View Here</a></p>');
});

session is present inside request object. So assign the string or the value to req.session.sessionName

Fetching session value in Express: Node.js
app.js

1
2
3
4
5
6
app.get('/user', function(req, res){
if(req.session.name)
 res.send(req.session.name+'<br /><a href="/logout">Logout</a>');
else
 res.send('user logged out!');
});

Here we check if the req.session.name has been set. If set, we show link to logout and also show current value present in the session variable. If the user is coming from /logout page, then we show “user logged out!” message.

destroy session value in Express: Node.js
app.js

1
2
3
4
app.get('/logout', function(req, res){
req.session.destroy();
res.send('<br />logged out!<br /><a href="/user">Check Session</a>');
});

Once the user clicks on /logout we destroy all the session by using req.session.destroy() We also give link to /user page, to check the fact that the session has already been destroyed.

Sessions In Express: Node.js


[youtube https://www.youtube.com/watch?v=vmDCakoxdwY]

YouTube Link: https://www.youtube.com/watch?v=vmDCakoxdwY [Watch the Video In Full Screen.]



Note: Make sure to have good session secret key – a combination of alphanumeric plus special characters. And make sure not to reveal it to anyone. Because, using this secret key / hash, someone with bad intention could possibly revoke the session and use your application as an authentic user, if care is not taken!

The main difference with cookie and a session is – session is stored on the server side and cookie on the client side.