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.
nodejs-session-2



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.

package.json

{
  "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.
nodejs-session

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

app.js

/*
* Author: Rohit Kumar
* Date: 03-09-2015
* Website: iamrohit.in
* 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
app.use(bodyParser.urlencoded({
  extended: true
}));
 
app.get('/',function(req,res){
   if(!req.session.name && !req.session.email) {
       res.render('index');
    } else {
        res.render('index', {name:req.session.name, email:req.session.email});
    }
});
 
// create session
app.post('/',function(req,res){
  if(req.body.name && req.body.email) {
        req.session.name = req.body.name;
        req.session.email = req.body.email;
        result = req.session;
  }
   res.redirect('/');
});
 
//destroy session
app.get('/destroy', function(req, res) {
   req.session.destroy(function(err){
      if(err){
        console.log(err);
      }
      else
      {
        res.redirect('/');
      }
    });
});
 
// 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 http://www.iamrohit.in/jade-node-template-engine-with-expressjs-example/

index.jade

doctype html
html(lang='en')
  head
    meta(charset='utf-8')
    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='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css')
  body
    .panel.panel-primary(style='width:50%;margin:0 auto; margin-top:10%')
      .panel-heading
        h3 Session Handling using Nodejs & Express 4
      .panel-body(style='height:40%; text-align:center;')
        p#msg.bg-info
        form#emailForm.form-horizontal(role='form', method='post')
          .form-group
            label.control-label.col-sm-2(for='name') Name:
            .col-sm-10
             if(!name)
              input.form-control(type='text', name='name', placeholder='Enter name', required='required')
             else
               h4 #{name}
          .form-group
            label.control-label.col-sm-2(for='email') Email:
            .col-sm-10
             if(!email)
              input.form-control(type='email', name='email', placeholder='Enter email', required='required')
             else
               h4 #{email}
          .form-group
            .col-sm-offset-2.col-sm-10
             if(!name && !email)
              button#send.btn.btn-primary.btn-lg(type='submit')
                |  Create Session
             else
               a(href="/destroy" class="btn btn-primary btn-lg") 
                   span Destroy Session  
    script(src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js')
    script(src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js')

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 socket.io

    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(‘socket.io’);

    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(‘socket.io’)(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){

    res.io = io;
    next();
    });

    app.use(device.capture());
    app.use(useragent.express());
    //app.use(logger(‘dev’));

    app.disable(‘x-powered-by’);

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

    var sessionStore = new MySQLStore(dbconfig);
    // required for passport
    app.use(session({
    secret: ‘mysecret’,
    resave: false,
    store: sessionStore,
    saveUninitialized: false,
    }));
    // session secret
    app.use(passport.initialize());
    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();
    next();
    });

    app.use(helmet());

    app.use(‘/’, routes);

    app.use(‘/modal’, modal);
    app.use(function(req,res,next){
    res.locals.isAuthenticated = req.isAuthenticated();
    next();
    });
    // 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;
    next(err);
    });

    // 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 = socket.id;
    //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 = ”;

    }else{
    /// 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.