After learning about cookies, lets look briefly about sessions in Express applications.
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]
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.
Error: Most middleware (like session) is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.
@Pradana, Thanks for pointing that out. Node implemented it with newer updates. Thanks for the links – will be helpful for others too.