Skip to main content
session-management-nodejs

NodeJS Session Example Using Express Session

This tutorial help to understand Session management in the Nodejs Application Using Express Session. We will create expressjs framework application with express-session. The express-session is a nodejs package that helps to manage sessions in the nodejs application.

I have already shared tutorial How to Use Local Storage and Session Storage In Angular 4.

I am using latest nodejs express 4 framework. The previous version of Express framework which was express 3, The Express 3 has been deprecated many dependencies like ‘bodyParser’, ‘logger’ etc.

What are the differences of Express 3 and Express 4

There is the following change will happen into migration from expressjs 3 to express 4.

Express 3Express 4
express.bodyParserbody-parser and
multer
express.compresscompression
express.cookieSessioncookie-session
express.cookieParsercookie-parser
express.loggermorgan
express.sessionexpress-session
express.faviconserve-favicon
express.responseTimeresponse-time
express.errorHandlererrorhandler
express.methodOverridemethod-override
express.timeoutconnect-timeout
express.vhostvhost
express.csrfcsurf
express.directoryserve-index
express.staticserve-static

Why Do We Use Session in Web Application ?

Session help to store data across application and pages into the server-side. The web application worked upon HTTP protocol. The HTTP is stateless So the application doesn’t know about the previous request or activity, The Session help to solve this problem.

Different Ways to Store Session in Nodejs

You can store sessions following ways into the ExpressJS application. These are common ways to store session data in any programming language.

  • Cokkie : You can store session into cookie, but it will store data into client side.
  • Memory Cache : You can also store session data into cache.As we know, Cache is stored in memory.You can use any of the cache module like Redis and Memcached.
  • Database :The database is also option to store session data server side.

Nodejs Session Connection with MySQL

Nodejs have mysql module to connect nodejs application with mysql.We will install ‘mysql’ package and add below code into server.js file to create db connection.

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '',
  database : 'dummy_db'
});

connection.connect(function(err) {
  if (err) throw err
  console.log('You are now connected...')
})

Nodejs Session Connection with Memcached

The nodejs have connect-memcached module to connect Memcached with nodejs application.We can use connect-memcached to store session into memory.

var MemcachedStore = require('connect-memcached')(session);
 
app.use(cookieParser());
app.use(session({
      secret  : 'some-private-key',
      key     : 'test',
      proxy   : 'true',
      store   : new MemcachedStore({
        hosts: ['127.0.0.1:11211'], //Memcached server host url
        secret: '123, ABC' // Optionally use transparent encryption for memcache session data 
    })
}));

Express Session Example

We will create an Expressjs application from scratch. This Expressjs application example has set session, get session value and destroy session value from session variables.

The express-session package have inbuilt method to set, get and destroy session.

Step 1: Create a folder 'node-express-session' and go to the folder path, Now create package dependency file using npm.

npm init

Above command will create package.json file into 'node-express-session' folder. We will add below code into package.json file.

{
  "name": "node-express-session",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": {
    "name": "Adam",
    "email": "[email protected]",
    "url": "http://js-tutorials.com/"
  },
  "license": "MIT",
  "dependencies": {
    "body-parser": "^1.18.3",
    "express": "^4.16.3",
    "express-session": "^1.15.6",
    "random": "^2.0.12"
  }
}

Now we will run below command to install dependencies:

npm install

Above command install all dependencies packages into node_modules/ folder, that are defined package.json file.

We will create express server along with ‘express-session’ package, The server help to run application:

var express = require('express');
var session = require('express-session');
var app = express();
var random = require("random");
app.use(session({resave: true, saveUninitialized: true, secret: 'XCR3rsasa%RDHHH', cookie: { maxAge: 60000 }}));

var server = app.listen(3000,  "127.0.0.1", function () {

  var host = server.address().address
  var port = server.address().port

  console.log("Example app listening at http://%s:%s", host, port)

});

Created ‘express-session’ instance and configure session object.We have also set max-age of session cookie, so that session cookie automatically expired after that time duration.

How To Set Session Data Using Express Session

Created rest call to set session data , You can use same method to any subsequent call to set session data into nodejs application.

var sessionData
app.get('/set_session',function(req,res){
  sessionData = req.session;
  sessionData.user = {};
  let username = "adam";
  sessionData.user.username = username;
  sessionData.user.salary = random.int(55, 956);
   console.log("Setting session data:username=%s and salary=%s", username, sessionData.user.salary)

 // res.end('Saved session and salary : ' + sessionData.username);
 res.json(sessionData.user)
});

The sessionData variable will contain session data.We have used random module to set random number into session. It’s just testing purpose, You can remove them.

How To Get Session Data Using Express Session

Created rest call to get session data which was stored into session object, if found then you will get value otherwise undefined value.

app.get('/get_session',function(req,res){
  sessionData = req.session;
  let userObj = {};
  if(sessionData.user) {
     userObj = sessionData.user;
  }
  res.json(userObj)
});

How To Destroy Session Data Using Express Session

We will use express session destroy() method to delete session data from variable, The session data not found: You will get error otherwise send "Success destroy" message.

app.get('/destroysession',function(req,res){
    sessionData = req.session;
    
    sessionData.destroy(function(err) {
        if(err){
            msg = 'Error destroying session';
            res.json(msg);
        }else{
            msg = 'Session destroy successfully';
            console.log(msg)
            res.json(msg);
        }
    });
});

2 thoughts to “NodeJS Session Example Using Express Session”

Leave a Reply

Your email address will not be published. Required fields are marked *