Express Session Tutorial Node.js

In this tutorial, I’m going to share how to use session in the express. We know that a session is a way to store information (in variables) to be used across multiple pages. We will do a form validation using session.

Table of Contents

  1. Create Project & Install Dependencies
  2. Create server.js
  3. Make a View File
  4. Register Route and Set Validation
  5. Run and Test

Step 1 : Create Project & Install Dependencies

Go to your workplace and create a project. After creating the project, navigate to the project folder. We have to create a package.json file. Create the file and paste this code to that file:

  "name": "nodejs-express-session",
  "version": "1.0.0",
  "description": "Nodejs Express Sesssion Tutorial",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon server"
  "dependencies": {
    "body-parser": "*",
    "cookie-parser": "*",
    "express": "*",
    "express-hbs": "*",
    "path": "*",
    "express-session": "*",
    "express-validator": "*"
  "keywords": [
  "author": "Md. Obydullah",
  "license": "ISC"

Run this command to install the dependencies:

npm update

We need to install nodemon server too. Let’s install this by this command:

npm install nodemon --save-dev

We have installed all dependencies.

Step 2 : Create server.js

In the root directory create a file called “server.js“. Then paste this code:

const express =  require('express');
const cookieParser =  require('cookie-parser');
const bodyParser =  require('body-parser') ;
const hbs = require('express-hbs');
const path = require('path');
const expressValidator =  require('express-validator') ;
const session =  require('express-session') ;
const user = require('./routes/user.route');

const app = express();
const PORT = 3000;


app.engine('hbs', hbs.express4({
   partialsDir: __dirname + '/views'
 app.set('view engine', 'hbs');
 app.set('views', __dirname + '/views');

app.use(bodyParser.urlencoded({extended: true}));

app.use(session({secret: 'obydul', saveUninitialized: false, resave: false}));


app.get('/', function(req, res){

app.listen(PORT, function(){
  console.log('Server is running on',PORT);

Here, we used HBS as view engine . We can also use EJS. We have set public folder for static files such as images, css, js etc.

Step 3 : Make a View File

Create a folder named “views” in the root directory. Under the views folder create “add.hbs” file and paste this code:

    <title>Add User</title>
    <link href="" rel="stylesheet" type="text/css">
    <div class="container"  style="margin-top: 40px;">
          {{# if errors }}
            {{# each errors }}
                <p class="alert alert-danger">{{ this.msg }}</p>
      <div class="panel panel-primary">
        <div class="panel-body">
          <form method="post" action="/user/add">
            <div class="form-group">
              <label class="col-md-4">Name</label>
              <input type="text" class="form-control" name="name"/>
            <div class="form-group">
              <label class="col-md-4">Email</label>
              <input type="text" class="form-control" name="email"/>
              <div class="form-group">
                <button type="submit" class="btn btn-success">Add</button>

Step 4 : Register Route and Set Validation

Make a folder named “routes” in the root directory. Go to the folder and create a file called “user.route.js“. Then open user.route.js and paste this code:

const express = require('express');
const router =  express.Router();

router.get('/', function(req, res){
   res.render('add', { success: req.session.success, errors: req.session.errors });
   req.session.errors = null;
});'/add', function(req, res) {
   let name =;
   let email =;

   req.checkBody('name', 'Name is required').notEmpty();
   req.checkBody('email', 'Email is required').notEmpty();

   var errors = req.validationErrors();
      req.session.errors = errors;
      req.session.success = false;
      req.session.success = true;

module.exports =  router;

In this file the session will be set.

Step 5 : Run and Test

Run the project by typing this command:

npm start

Now visit http://localhost:3000/user. You will see a form. Then click the “Add” button without filling-up the fields. If everything is ok, you will see the notice.

Here’s the file structure of the project:

Thank you. ?

Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.