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
- Create Project & Install Dependencies
- Create server.js
- Make a View File
- Register Route and Set Validation
- 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": [
"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:
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:
<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:
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:

Comment
Preview may take a few seconds to load.
Markdown Basics
Below you will find some common used markdown syntax. For a deeper dive in Markdown check out this Cheat Sheet
Bold & Italic
Italics *asterisks*
Bold **double asterisks**
Code
Inline Code
`backtick`Code Block```
Three back ticks and then enter your code blocks here.
```
Headers
# This is a Heading 1
## This is a Heading 2
### This is a Heading 3
Quotes
> type a greater than sign and start typing your quote.
Links
You can add links by adding text inside of [] and the link inside of (), like so:
Lists
To add a numbered list you can simply start with a number and a ., like so:
1. The first item in my list
For an unordered list, you can add a dash -, like so:
- The start of my list
Images
You can add images by selecting the image icon, which will upload and add an image to the editor, or you can manually add the image by adding an exclamation !, followed by the alt text inside of [], and the image URL inside of (), like so:
Dividers
To add a divider you can add three dashes or three asterisks:
--- or ***

Comments (0)