JavaScript

Session Management in Node.js

Hello. This tutorial will explain session management in the node.js application.

1. Introduction

Session management is an important part of any application that helps the application track the users and their activities. To understand this we will be using a cookie which is key-value pair stored in the browser. The browser then attaches the cookies to every HTTP request sent to the server.

1.1 Setting up Node.js

To set up Node.js on windows you will need to 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.

Node.js session - npm installation
Fig. 1: Verifying node and npm installation

2. Session Management in Node.js

To set up the application, we will need to navigate to 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 the implementation

Let us write the different files which will be required for practical learning.

2.1.1 Setting up dependencies

Navigate to the project 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 required dependencies.

package.json

{
  "name": "session-management-app",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "start": "nodemon server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cookie-parser": "^1.4.5",
    "express": "^4.17.1",
    "express-session": "^1.17.2"
  },
  "devDependencies": {
    "dotenv": "^10.0.0",
    "nodemon": "^2.0.12"
  }
}

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.1.2 Creating controller

In the root folder add the following content to the index file. The file will be responsible to initialize the imports and routes. Remember to create a .env file at the same location and specify the sensitive information such as session-secret, application port number, etc.

server.js

if (process.env.NODE_ENV !== "production") {
  require("dotenv").config();
}

// imports
const express = require("express");
const session = require("express-session");
const cookieParser = require("cookie-parser");

const app = express();
app.use(cookieParser());
// session configuration
app.use(
  session({
    secret: process.env.SESSION_SECRET || "8unto0n4oc7903zm",
    resave: false,
    saveUninitialized: false,
  })
);

const appUsr = {};

// routes

// http post - http://localhost:7501/login?name=daniel
app.post("/login", (req, res) => {
  appUsr.name = req.query.name;

  // some business logic here ...
  req.session.user = appUsr;
  req.session.save();
  return res.status(201).json({ info: "User logged in" });
});

// http get - http://localhost:7501/user
app.get("/user", (req, res) => {
  if (req.session.user != null) {
    return res
      .status(200)
      .json({ info: "User profile info", data: req.session.user });
  } else {
    return res.status(200).json({ info: "No data present in session" });
  }
});

// http post - http://localhost:7501/logout
app.post("/logout", (req, res) => {
  req.session.destroy();
  return res.status(204).json({ info: "User logged out" });
});

// start server
const port = process.env.APPLICATION_PORT || 7501;
app.listen(port, () => {
  console.log("Server listening at http://localhost:%s", port);
});

3. Run the Application

To run 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 a port number read from the .env file or 7501.

Node.js session - start the app
Fig. 2: Starting the application

4. Demo

You are free to use postman or any other tool of your choice to make the HTTP request to the application endpoints.

Endpoints

// http post - http://localhost:7501/login?name=daniel
// http get - http://localhost:7501/user
// http post - http://localhost:7501/logout

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 about session management in the nodejs application. You can download the source code and the postman collection from the Downloads section.

6. Download the Project

This was a tutorial to implement session management in a nodejs application.

Download
You can download the full source code of this example here: Session Management in Node.js

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