Skip to content
Related Articles

Related Articles

Session Cookies in NodeJS
  • Difficulty Level : Expert
  • Last Updated : 05 Feb, 2021

HTTP protocol: It is the backbone of the internet every single request from the client for particular contains several HTTP headers and that contains all the information of the request. This protocol is the foundation of the data exchange over the internet but the HTTP protocol is the stateless protocol means this protocol cannot be able to maintain the past requests of the particular client to the server. It means we have to give again and again authorized requests in order to move forward to the next page of the particular page of a web application then how to overcome this problem. The answer is cookies and sessions. Cookies and sessions make the HTTP protocol stateful protocol. 

Session cookies: Session cookies are the temporary cookies that mainly generated on the server-side.The main use of these cookies to track all the request information that has been made by the client overall particular session. The session is stored for a temporary time when the user closes the browser session automatically destroys it. In this article, we will be using external file storage in order to store session cookies. Example of session cookies the most common example of session cookies are an e-commerce website. All e-commerce website initializes a session when a new user starts the particular e-commerce website. When a session is created after successful authorization a unique session id is created on the client-side in the form of a cookie. So that after the first request this generated cookie on the client-side will help for authentication of the user with the session on the client-side and session track all the new request’s information and response the past tracked information to the client.

Installing Modules:

  • express.js: Express.js framework used for handling multiple requests.
npm install express
  • cookie-parser: The cookie-parser module used to parse the incoming cookies.
npm install cookie-parser
  • express-session: This express-session module used for session management in NodeJS.
npm install express-session
  • session-file-store: This module helps to create a new file-store for the new session.
npm session-file-store

Project Structure: Our project structure will look like this:



Filename: index.js

Javascript




// Importing express module
const express = require("express")
  
// Importing express-session module
const session = require("express-session")
  
// Importing file-store module
const filestore = require("session-file-store")(session)
  
const path = require("path")
  
// Setting up the server
var app = express()
  
// Creating session 
app.use(session({
    name: "session-id",
    secret: "GFGEnter", // Secret key,
    saveUninitialized: false,
    resave: false,
    store: new filestore()
}))
  
// Asking for the authorization
function auth(req, res, next) {
    // Checking for the session
    console.log(req.session)
  
    // Checking for the authorization
    if (!req.session.user) {
        var authHeader = req.headers.authorization;
        console.log(authHeader);
        var err = new Error("You are not authenticated")
        res.setHeader("WWW-Authenticate", "Basic")
        err.status = 401
        next(err)
  
        var auth = new Buffer.from(authHeader.split(' ')[1],
            "base64").toString().split(":")
  
        // Reading username and password
        var username = auth[0]
        var password = auth[1]
        if (username == "admin2" && password == "password") {
            req.session.user = "admin2"
            next()
        }
        else {
            // Retry incase of incorrect credentials
            var err = new Error('You are not authenticated!');
            res.setHeader("WWW-Authenticate", "Basic")
            err.status = 401;
            return next(err);
        }
    }
    else {
        if (req.session.user === "admin2") {
            next()
        }
        else {
            var err = new Error('You are not authenticated!');
            res.setHeader("WWW-Authenticate", "Basic")
            err.status = 401;
            return next(err);
        }
    }
}
  
// Middlewares
app.use(auth)
app.use(express.static(path.join(__dirname, 'public')));
  
// Server setup
app.listen(3000, () => {
    console.log("Server is Starting")
})

Run index.js file using below command:

node index.js
  • Open any browser with http://localhost:3000 location in a private window(in order to avoid a saved password and username). A pop will occur near the address bar. Fill in the username and password that are mention in the code as shown below:

  • If the entered username and password match the mention location index.html will render on the browser.

Explanation:

  • When we type Run index.js file using node index.js command we will find a response that is given below for new user:

  • After filling in the matched password and username a new session is generated in the directory which keeps track of all the successful requests made by the client.

  • This session file contains all the session records i.e information of the particular client when the client made the first request and many more as shown below:
{"cookie":{"originalMaxAge":null,
  "expires":null,"httpOnly":true,"path":"/"},
"user":"admin","__lastAccess":1610430510130}
  • The server response to the client to set a cookie for this particular session. So when a client makes another request to the server. The request header contains a cookie that contains session-id that has already created on the server-side. The request.headers will look like the following:

  • After successfully matching both cookie session-id and file store session-id server returns skip the authorization in the above code and Render index.html file to the user. Successfully matching session’s id is shown below:

My Personal Notes arrow_drop_up
Recommended Articles
Page :