Latest Code Tutorials

Express Session Example From Scratch

Node js express sessions tutorial


Get real time updates directly on you device, subscribe now.

Express Session Example From Scratch is the topic we will discuss today. 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 Tutorial

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

Express Session Example

We will take an example of form validation. We will display validation message via a session on the frontend. So let us get started.

Step 1: Create a folder and install dependencies.

Create the project folder and 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 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 the http://localhost:3000 You can see there, Node.js server is running on Port: 3000.

Next step is that we need 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 views folder yet but we will in a moment. We have used Express Handlebars as a templating engine. 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 views folder called partials. We can use this to define the header.hbs and footer.hbs file.

Also, make one folder called public and in that create one folder named css and in that 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 route for our application.

Create one folder inside root called routes and in that 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 in the server.js file.

// server.js

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


Go to the 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'/add', function(req, res) {
   let name =;
   let 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 is there any errors, then it will store in the session and redirect us to the add view with the errors.

Related Posts
1 of 10

Now, just write code in 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, then it will store the values in the session and gives us an error.

Express handlebars tutorial

So this is how we can use the sessions. I have already put the code on Github. Finally, our Express Session Example is over.

Fork Me On Github

  1. Tula says

    I got this error when I run this example and go to http://localhost:3000/user.

    “Error: ENOENT: no such file or directory, lstat ‘C:\Users\cuyi\Desktop\node\expresses-session-example\views\partials’ “

    1. Krunal says

      Please make a directory inside views folder called partials.

Leave A Reply

Your email address will not be published.

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