JavaScript

Express.js Sessions Tutorial

Hello! In this tutorial, we will explain the Express.js sessions. We will understand how to manage sessions in a Node.js application. HTTP is a stateless protocol and to manage sessions in a Node.js application we will use the express-session dependency.

1. Introduction

To set up this application we will put the expression-session and cookie-parser middleware dependencies in place. But before doing any programming stuff we will need to install Node.js on windows and you can download the installer from this link. Click on the installer (also include the NPM package manager) for your platform and run the installer to start with the Node.js setup wizard. Follow the wizard steps and click on Finish when it is done. If everything goes well you can navigate to the command prompt to verify if the installation was successful as shown in Fig. 1.

express js sessions - npm installation
Fig. 1: Verifying node and npm installation

2. Express.js Sessions Tutorial

To set up the Express.js server, we will need to navigate a path where our project will reside. For programming stuff, I am using Visual Studio Code as my preferred IDE. You’re free to choose the IDE of your choice.

2.1 Setting up dependencies

Navigate to a directory and run npm init -y to create a package.json file. This file holds the metadata relevant to the project and is used for managing the project dependencies, script, version, etc. Add the following code to the file wherein we will specify the dependencies.

package.json

{
  "name": "expressjs-session",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "express-session": "^1.17.2",
    "cookie-parser": "^1.4.5"
  },
  "devDependencies": {
    "nodemon": "^2.0.7"
  }
}

To download the dependencies navigate to the directory path containing the file and use the npm install command. If everything goes well the dependencies will be loaded inside the node_modules folder and you are good to go with the further steps.

2.2 Creating an Express server

Add the following programming stuff to the index.js file and we will import the expression-session and cookie-parser middleware modules. Whenever a user will make an introductory request a new session will be created for the user. Now when another request from the same user comes, the application will already have their session information stored.

index.js

const express = require('express');
const cookieParser = require('cookie-parser');
const session = require('express-session');

const app = express();
app.use(cookieParser());
// using secret for cookie handling
app.use(session(
    {
        secret: 'Your_Secret_Key',   // used to sign the session id cookie
        saveUninitialized: true,     // forces the session that is "uninitialized" to be saved to the store
        resave: false                     // forces the session to be saved back to the session store, even if a session was not modified by request
    }
));

// endpoint
// http://localhost:4001/session
app.get('/session', function (req, res) {
    if (req.session.page_views) {
        // incrementing the page views counter by 1
        req.session.page_views++;
        res.status(200).json({info: `Welcome to this tutorial. Visit counter : ${req.session.page_views}`});
    } else {
        // introductory request
        // setting the page views counter to 1
        req.session.page_views = 1;
        res.status(200).json({info: 'Welcome to this tutorial for the first time'});
    }
});

const PORT = process.env.port || 4001;
app.listen(PORT, () => {
    console.log(`Server started on port ${PORT}`);
});

3. Run the Application

To launch the application navigate to the project directory and enter the following command as shown in Fig. 2. If everything goes well the application will be started successfully on port number 4001.

express js sessions - launch the app
Fig. 2: Launch the application

4. Project Demo

When the application is started, open the browser and enter the following url – http://localhost:4001/session. If the request will be the first the following message will be shown to the user – Welcome to this tutorial for the first time and if the user sends the repeated requests the message with display a page visit counter. That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

5. Summary

In this tutorial, we learned:

  • Steps to setup Node.js
  • Sample programming to understand Session management in Express.js server

You can download the source code of this tutorial from the Downloads section.

6. Download the Project

This was a programming tutorial on session management in an Express.js server.

Download
You can download the full source code of this example here: Express.js Sessions Tutorial

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button