What is Session in Express and How to Use in Node.js

Express Session Tutorial Example From Scratch

As we all know, HTTP is a stateless protocol. We need to identify the request and associate each request to the user if the user has already arrived before. So to persist data across the multiple pages, we use sessions.

Express session

To create a session in the express framework, use the express-session package. The express-session module provides a method and properties that can set and get the values from the session.

Express Sessions are used in a Node js web application to maintain the state of a user. To install express-session, type the npm install express-session –save command in your terminal or command-line tools.

The most used case scenario of the session is Authentication System. When users log in to any system, they can see their activity based on their ID. So we need to store the user’s ID into a session and then query that ID to display different information about that User.

We will take the example of form validation. We will display validation messages via a session on the front end. So let us get started step by step.

Step 1: Create a folder and install dependencies.

Create the project folder, go into that, and hit the following command.

npm init

It will create a package.json file and write the following code in it.

  "name": "sessionexpress",
  "version": "1.0.0",
  "description": "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": "Krunal Lathiya",
  "license": "ISC"

It will install the Express web framework, express-session, and other packages.

Step 2: Make a server.js file and start the node server.

In a root directory, create one file called server.js.

// server.js

const express =  require('express');
const cookeParser =  require('cookie-parser');
const bodyParser =  require('body-parser') ;
const hbs = require('express-hbs');
const expressValidator =  require('express-validator') ;
const session =  require('express-session') ;

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

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

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

Go to http://localhost:3000. You can see there the Node.js server is running on Port: 3000.

The next step is to set the view engine and middlewares for our application. Add the following code to the server.js file.

// server.js

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

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

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


We have not created the views folder yet, but we will in a moment. We have used Express Handlebars as a templating engine. But, of course, you can use EJS also. Here we have used body-parser middleware and also used cookie-parser. 

Then use express session, which requires an object as an argument to initialize it. Then use a flash package to display an error or success message.

Step 3: Making required directories.

In the root folder, make one directory called views, and in that shape, one file called add.hbs. Also, make one directory inside the views folder called partials. Then, we can define the header.hbs and footer.hbs file.

Also, make one folder called public and create one folder named css and put the bootstrap.min.css file.

<!-- add.hbs -->

    <title>Add Info</title>
    <link href="/css/bootstrap.min.css" rel="stylesheet" type="text/css">
    <div class="container">
      <div class="panel panel-primary">
        <div class="panel-heading">
           Add User
        <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-primary">Add User</button>

Define the route for our application.

Create one folder inside root called routes and make one file called user.route.js file. We need to define here get and post routes for our application.

// user.route.js

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

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

module.exports =  router;

Now, we need to import this route into the server.js file.

// server.js

const user = require('./routes/user.route');


Go to http://localhost:3000/user. You will see a form like this.

express session middleware example tutorial


Step 4: Server-side validation.

In the routes >> user.route.js file, paste the following code. We have just defined the post route.

// user.route.js

router.post('/add', function(req, res) {
   let name = req.body.name;
   let email = req.body.email;
   req.checkBody('name', 'Name is required').notEmpty();
   req.checkBody('email', 'Email is required').notEmpty();
   req.checkBody('email', 'Please enter a valid email').isEmail();
   const errors = req.validationErrors();
      req.session.errors = errors;
      req.session.success = true;

So, if there are any errors, it will store them in the session and redirect us to the add view with the errors.

Now, write the add.hbs file to display the errors.

<!-- add.hbs -->

 {{# if errors }}
     {{# each errors }}
          <p class="alert alert-danger">{{ this.msg }}</p>

Now, go to the http://localhost:3000/user. If you submit the form without any values, it will store the values in the session and give us an error.

Express handlebars tutorial

So this is how we can use the sessions. I have already put the code on Github. That’s it for Express Session tutorial.

Fork Me On Github


Leave A Reply

Please enter your comment!
Please enter your name here

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