This tutorial explains the basic concept of ExpressJS session management. Sessions are an important part of web application. HTTP being stateless, to maintain state across requests among many other approaches, sessions and cookies is one approach.
In this article we will explore how we can make use of Node package express-session
to maintain session in a ExpressJS based web application.
Setting up the app
Let us create an empty Node project using npm as shown below:
$ mkdir session-demo $ cd session-demo $ npm init name: (session-demo) version: (1.0.0) description: Session demo for expressjs app entry point: (index.js) test command: git repository: keywords: author: mohamed sanaulla license: (ISC) About to write to G:\node\session-demo\package.json: { "name": "session-demo", "version": "1.0.0", "description": "Session demo for expressjs app", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "mohamed sanaulla", "license": "ISC" } Is this ok? (yes)
Install relevant node packages for Express and Express session:
$npm install express --save $npm install express-session --save
Let us create a simple Express app as shown below:
//Filename - index.js var express = require('express'); var session = require('express-session'); var app = express(); app.get("/", function(req, res){ res.json({ "status" : "ok" }); }); app.listen(3300, function (){ console.log("Server started at: http://localhost:3300"); });
The above app returns a JSON object on calling http://localhost:3300/. Its a very simple example.
ExpressJS Session Management Example
In the below example, I am using session to record frequency of API invocation for a user. express-session by default stores the session data in memory. It provides support for replacing this default storage with different storage options as listed here.
express-session accepts a few properties in the options object. This object is passed while setting up the session with express app as shown below:
var express = require('express'); var session = require('express-session'); var app = express(); var sessionOptions = {}; app.use(session(sessionOptions));
Different properties of the sessions options object are:
- cookie: Options object for the session ID cookie. The default value is
{ path: '/', httpOnly: true, secure: false, maxAge: null }
. - genid: Function to generate the session ID. Default is to use uuid
- name:The name of the session ID cookie to set in the response (and read from in the request).
- proxy: Trust the reverse proxy when setting secure cookies.
- resave: If true forces a session to be saved back to store even if it was not modified in the request.
- rolling: Forces a cookie to be set on every request.
- saveUninitialized: If true it forces a newly created session without any modifications to be saved to the session store.
- secret: It is a required option and is used for signing the session ID cookie.
- store: Session store instance. Default is to use memory store.
- unset: Controls the handling of session object in the store after it is unset. Either
delete
orkeep
the session object. Default is to keep the session object
Let us update the express app code to increment the frequency of the API invocation per user and record it in the session as shown below:
var express = require('express'); var session = require('express-session'); var app = express(); var sessionOptions = { secret: "secret", resave : true, saveUninitialized : false }; app.use(session(sessionOptions)); app.get("/", function(req, res){ if ( !req.session.views){ req.session.views = 1; }else{ req.session.views += 1; } res.json({ "status" : "ok", "frequency" : req.session.views }); }); app.listen(3300, function (){ console.log("Server started at: http://localhost:3300"); });
Run the above application by using command: node .
from the app root directory. Continuously load the URL: http://localhost:3300/ and see the frequency
changing.
Conclusion
This was a very simple example of expressjs session management. I hope the expressjs session example I have provided is very helpful. It is a pre-requiste information to be known before working on authentication related features as authentication uses session to record authenticated user info. We will also see how to use different session stores i.e mysql, MongoDB and so on.