AppDividend
Latest Web Development Tutorials

Express Session Example From Scratch

Node js express sessions tutorial

171

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": "*"
  },
   "devDependencies":{
     "nodemon":"*"
  },
  "keywords": [
    "Express",
    "Node.js",
    "Session"
  ],
  "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){
   res.send('hello');
});

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.

Related Posts
1 of 6
// server.js

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

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

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

app.use(expressValidator());

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 -->

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

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

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

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

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();
   if(errors){
      req.session.errors = errors;
      res.redirect('/user');
   }
   else{
      req.session.success = true;
      res.redirect('/');
   }
   
});




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

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>
     {{/each}}
 {{/if}}

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

2 Comments
  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.