Session Handling Using Nodejs And Express 4 With Jade Template Engine

This tutorial will explain you some basics of Session in Nodejs and Express 4, Here you’ll learn how to store, retrieve and destroy session value on your web page in Nodejs and Express 4 .

Session plays very important role in any web based application to travel user’s sensitive or non sensitive data from page to page.

We all know lot’s of module of Express 3 has been deprecated, So here i am using all latest modules with Express 4.

First of all create you dependency manager file called package.json which will help you to install all the require dependencies in our project directory.


  "name": "NodeJs-Session",
  "version": "0.0.1",
  "description": "Session Handling using Nodejs & Express",
  "dependencies": {
    "body-parser": "~1.13.1",
    "express": "^4.13.3",
    "express-session": "^1.11.3",
    "jade": "^1.11.0"

After that run below command to install dependencies from package.json file

npm install

Create views folder in your project directory where you’ll create you html pages, your project directory structure will be.

Create file app.js where we are going to write our server side script to start server and handle session.


* Author: Rohit Kumar
* Date: 03-09-2015
* Website:
* App Name: Session Handling using Nodejs & Express 4
* Description: This is a simple script to demonstrate session handling in nodejs and express 4 
var http=require('http');
var express=require('express');
var path=require('path');
var bodyParser = require('body-parser');
var session = require('express-session');
var app=express();
var port = Number(process.env.PORT || 5000);
app.use(session({secret: 'ABCDEF123456789', cookie: { maxAge: 60000 }})); // Set some rendom secret value for your session
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(bodyParser.json()); // to support JSON-encoded bodies
  extended: true
   if(! && ! {
    } else {
        res.render('index', {,});
// create session'/',function(req,res){
  if( && { =; =;
        result = req.session;
//destroy session
app.get('/destroy', function(req, res) {
// Starting server
var server = http.createServer(app).listen(port, function() {
console.log("Listening on "+port);

Create index.jade file in views folder. I am using jade template engine, You can learn more ablout jade form here


doctype html
    meta(http-equiv='X-UA-Compatible', content='IE=edge')
    meta(name='viewport', content='width=device-width, initial-scale=1')
    title Session Handling using Nodejs & Express 4
    link(rel='stylesheet', href='')
    .panel.panel-primary(style='width:50%;margin:0 auto; margin-top:10%')
        h3 Session Handling using Nodejs & Express 4
      .panel-body(style='height:40%; text-align:center;')
        form#emailForm.form-horizontal(role='form', method='post')
            label.control-label.col-sm-2(for='name') Name:
              input.form-control(type='text', name='name', placeholder='Enter name', required='required')
               h4 #{name}
            label.control-label.col-sm-2(for='email') Email:
              input.form-control(type='email', name='email', placeholder='Enter email', required='required')
               h4 #{email}
             if(!name && !email)
                |  Create Session
               a(href="/destroy" class="btn btn-primary btn-lg") 
                   span Destroy Session  

Now all is done time to run our project.

cd YourProjectDirectory
node app.js

Note: This is storing session value for temporary bases whenever you restart your server session will be destroy, For storing session permanent bases you need to use redis or mongodb any other nosql database.

I hope this tutorial will help you to understand session handling in Nodejs and Express 4.

See demo and download source code by clicking on download button.

If you like this post please don’t forget to subscribe My Public Notebook for more useful stuff.

One Reply to “Session Handling Using Nodejs And Express 4 With Jade Template Engine”

  1. Hi,
    I am new to node js I have issue with session
    I am using nodejs with

    my app.js code is below

    const express = require(‘express’);
    const session = require(‘express-session’);
    const path = require(‘path’);
    const favicon = require(‘serve-favicon’);
    const logger = require(‘morgan’);
    const cookieParser = require(‘cookie-parser’);
    const bodyParser = require(‘body-parser’);
    const expressHbs = require(‘express-handlebars’);
    const validator = require(‘express-validator’);

    const socket_io = require(‘’);

    const routes = require(‘./routes/index’);
    const modal = require(‘./routes/modal’);

    const app = express();
    const passport = require(‘passport’);
    const flash = require(‘connect-flash’);

    const server = require(‘http’).Server(app);
    const io = require(‘’)(server);
    const device = require(‘express-device’);
    const useragent = require(‘express-useragent’);
    const csrf = require(‘csurf’);
    const helmet = require(‘helmet’);
    const MySQLStore = require(‘express-mysql-session’)(session);
    var dbconfig = require(‘./config/config’);
    //var dbmodal = require(‘./config/dbmodal’);
    var showtick = require(‘./config/showtickmodal’);

    // configuration ===============================================================
    // connect to our database
    require(‘./config/passport’)(passport); // pass passport for configuration

    // view engine setup
    app.engine(‘.html’,expressHbs({defaultLayout : ‘layout’,extname:’.html’}));
    app.set(‘view engine’, ‘.html’);
    app.locals.pretty = false;
    // uncomment after placing your favicon in /public
    //app.use(favicon(path.join(__dirname, ‘public’, ‘favicon.ico’)));
    app.use(function(req, res, next){ = io;



    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(express.static(path.join(__dirname, ‘public’)));

    var sessionStore = new MySQLStore(dbconfig);
    // required for passport
    secret: ‘mysecret’,
    resave: false,
    store: sessionStore,
    saveUninitialized: false,
    // session secret
    app.use(passport.session()); // persistent login sessions
    app.use(flash()); // use connect-flash for flash messages stored in session

    app.use(csrf({cookie: true}));

    app.use(function(req, res, next) {
    res.locals._csrf = req.csrfToken();


    app.use(‘/’, routes);

    app.use(‘/modal’, modal);
    res.locals.isAuthenticated = req.isAuthenticated();
    // routes ======================================================================
    require(‘./routes/routes.js’)(app, passport); // load our routes and pass in our app and fully configured passport
    // launch ======================================================================

    // catch 404 and forward to error handler
    app.use(function(req, res, next) {
    var err = new Error(‘Not Found’);
    err.status = 404;

    // error handlers

    // development error handler
    // will print stacktrace
    if (app.get(‘env’) === ‘development’) {
    app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render(‘error’, {
    message: err.message,
    error: err

    // production error handler
    // no stacktraces leaked to user
    app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render(‘error’, {
    message: err.message,
    error: {}
    io.on(‘connection’, function(socket){
    socket.on(‘chat message’, function(msg){
    console.log(‘chat message server on’);
    io.emit(‘chat message’, msg);
    socket.on(‘showtick’, function(msg){
    console.log(‘showtick server on’);
    io.emit(‘showlist’, msg);

    io.on(‘connection’, function(socket) {
    //console.log(‘session APp’+ JSON.stringify(sessionStore, null, 2) );
    var addedUser = false;
    var socketusers = {};
    var users = {};

    socket.emit(‘announcements’, { message: ‘A new user has joined!’ });
    socketusers.socketid =;
    //console.log(‘socket ‘+JSON.stringify(socketusers));
    socket.on(‘showtick’, function(msg) {
    socket.userid = msg.userid;
    //console.log(‘sessionID ‘+io.clients[sessionID]);

    //console.log(‘tests ‘+JSON.stringify(tests));
    var Sl = showtick.CallShowTick(msg,function(err, result){
    console.log(‘result ‘+ JSON.stringify(result, null, 3) );
    //console.log(‘CallShowTick In App.js’+JSON.stringify(result));
    //console.log(‘Count ‘+result.count);

    if(result.count > 0){
    //console.log(‘Count If’);
    var showcount = ”;

    /// console.log(‘Send Showticks ‘);
    socket.emit(‘showticks’, result);


    module.exports = {app: app, server: server};

    i want to connect socket on if user is logged in this(io.on(‘connection’, function(socket))

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.