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:

package.json
{
  "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": [
    "Express",
    "Node.js",
    "Session"
  ],
  "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:

server.js
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.use(express.static('public'));

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

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

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

app.use('/user',user);

app.get('/', function(req, res){
   res.send('Welcome!');
});

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:

add.hbs
<html>
  <head>
    <title>Add User</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" type="text/css">
  </head>
  <body>
    <div class="container"  style="margin-top: 40px;">
          {{# if errors }}
            {{# each errors }}
                <p class="alert alert-danger">{{ this.msg }}</p>
            {{/each}}
          {{/if}}
      <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>
            <div class="form-group">
              <label class="col-md-4">Email</label>
              <input type="text" class="form-control" name="email"/>
              </div>
              <div class="form-group">
                <button type="submit" class="btn btn-success">Add</button>
              </div>
          </form>
        </div>
      </div>
    </div>
  </body>
</html>

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:

user.route.js
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;
});

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();

   var errors = req.validationErrors();
   if(errors){
      req.session.errors = errors;
      req.session.success = false;
      res.redirect('/user');
   }
   else{
      req.session.success = true;
      res.redirect('/');
   }
});

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.