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.

Cookies In Express: Node.js

Cookies are one of the important recipe for building an effective web application.

cookies-express-nodejs

A cookie, also known as an HTTP cookie, web cookie, or browser cookie, is a small piece of data sent from a website you are surfing and stored in a user/client computer. Every time the user loads that website again, the browser sends this cookie back to the server to notify the website of the user’s previous activity.

This way, using cookie, we could track user activities like her navigational behaviors, previous purchases on our site or previous leads etc.

Setting Cookie in Express: Node.js
app.js

1
2
3
4
5
6
7
8
9
10
var express = require('express');
 
var app = express();
app.use(express.cookieParser());
 
app.get('/user/:user', function(req, res){
res.cookie('username', req.params.user)
    .send('<p>Cookie Set: <a href="/user">View Here</a>');
});
</p>

Using express’s cookieParser() middleware we can enable working with cookies.
Once the user navigates to /user/someUserName URL, the cookie is set with the name username and the value is actually fetched out of the request object’s params.

General Syntax for setting Cookie

res.cookie('cookieName', value, {expires: new Date() + 99999, maxAge: 99999});

Set a name to the cookie, give it some value. Also you can set the optional settings like, expiration date or the maxAge the cookie will be alive on the client computer.

Accessing Cookie in Express: Node.js
app.js

1
2
3
app.get('/user', function(req, res){
res.send(req.cookies.username);
});

Once the user visits /user route, we fetch the value present in the req.cookies.username and display it to the user.

Cookie In Express: Node.js


[youtube https://www.youtube.com/watch?v=mdvQ74KL-fU]

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



Note: We could see the value stored in a cookie, by using chrome’s console window and typing document.cookie

Clearning Cookie in Express: Node.js
app.js

1
2
3
4
app.get('/user', function(req, res){
res.clearCookie('username')
           .send(req.cookies.username);
});

You could remove a cookie by using clearCookie method of response object.

Once the cookie has been removed, you can set it again explicitly using Chromes console window.
Type: document.cookie = “username = Microsoft”
now refresh the browser, and you’ll see Microsoft being displayed!