The Wayback Machine - https://web.archive.org/web/20240901001653/https://www.geeksforgeeks.org/session-cookies-in-node-js/
Open In App

Session Cookies in Node.js

Last Updated : 07 Oct, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:



Similar Reads

Why are HTTP cookies used by Node.js for sending and receiving HTTP cookies?
The HTTP protocol is one of the most important protocols of the Application layer of the OSI model. The main use of this protocol is for sending hypertext information to the client to the server and server to the client to communicate on the World Wide Web. But, the HTTP protocol is a stateless protocol which means that this protocol cannot maintai
5 min read
Session Management using express-session Module in Node.js
Session management can be done in node.js by using the express-session module. It helps in saving the data in the key-value form. In this module, the session data is not saved in the cookie itself, just the session ID. Installation of express-session module: You can visit the link Install express-session module. You can install this package by usin
2 min read
What are the difference between session and cookies in PHP ?
A session is a way to store information (in variables) to be used across multiple pages. When a user visits a website and starts a new session, the server creates a unique session ID and stores it in a cookie on the user's computer. The server also creates a file on the server to store the session variables for that user. The session ID in the cook
5 min read
How to Set Cookies Session per Visitor in JavaScript?
Managing session cookies in JavaScript is essential for web developers to maintain user state and preferences across multiple sessions. The document. cookie property provides a basic mechanism for cookie management, utilizing JavaScript libraries or frameworks can offer enhanced security and flexibility. Table of Content Using the document.cookie P
4 min read
Difference Between Local Storage, Session Storage And Cookies
The HTTP protocol is one of the most important protocols for smooth communication between the server and the client. The main disadvantage of the HTTP protocol is that it is a stateless protocol, which means it does not track any kind of response or request by the server or the client. So to resolve this problem, we have Local Storage, Session Stor
6 min read
What is a session and how to start a session in PHP?
A session in PHP is a way to preserve data across subsequent HTTP requests. It allows information like user authentication status or user preferences to be stored and accessed throughout a user's interaction with a website. Starting a Session:To start a session in PHP, use the session_start() function at the beginning of your PHP script. This funct
2 min read
How to Expire Session After 1 Min of Inactivity in express-session of Express.js ?
To automatically expire sessions after 1 minute of inactivity in an Express.js application using express-session, configure the session settings with the cookie.maxAge and implement session touch logic to track activity. ApproachTo expire the session after 1 min of inactivity in the express-session of Express.js we use expires: 60000 in the middlew
2 min read
How to Clear Session Storage Data with Specified Session Storage Item?
JavaScript sessionStorage is a web storage technique that allows you to store data in a web browser. You can manually set and retrieve the values from it using some methods. The sessionStorage stores the data for a short amount of time until the browser tab or window gets closed. We will learn how to clear the session storage of a browser using Jav
2 min read
HTTP Cookies in Node.js
Cookies are small data that are stored on a client side and sent to the client along with server requests. Cookies have various functionality, they can be used for maintaining sessions and adding user-specific features in your web app. For this, we will use cookie-parser module of npm which provides middleware for parsing of cookies. First set your
4 min read
Node.js http2stream.session Method
The http2stream.session is an inbuilt application programming interface of class Http2Stream within http2 module which is used to get an reference to the Http2Session instance that owns this Http2Stream. Syntax: const http2stream.session Parameters: This method does not accept any parameter. Return Value: This method returns an reference to the Htt
3 min read
How to Use Session Variables with Node.js?
Session management is a crucial aspect of web application development, enabling you to store user data between HTTP requests. In Node.js, session management is often handled using the express-session middleware. This article will guide you through the process of setting up and using session variables in a Node.js application. Session ManagementSess
4 min read
PHP Cookies
A cookie in PHP is a small file with a maximum size of 4KB that the web server stores on the client computer. They are typically used to keep track of information such as a username that the site can retrieve to personalize the page when the user visits the website next time. A cookie can only be read from the domain that it has been issued from. C
5 min read
Express Cookie-Parser - Signed and Unsigned Cookies
A cookie is a piece of data that is sent to the client-side with a request and is stored on the client-side itself by the Web Browser the user is currently using. With the help of cookies - It is easy for websites to remember the user's information It is easy to capture the user's browsing history It is also useful in storing the user's sessions Th
5 min read
How to clear all cookies using JavaScript ?
Cookies provide a way for a client and server to interact and pass information via HTTP. This enables the client to store state information despite using HTTP which is a stateless protocol. When a browser requests a web page from a server, the server services the request and “forgets” about the visit. But it passes some information to the user’s br
2 min read
If we delete cookies of a site, we can still logged in without logging again
The facebook is coded in PHP and PHP was launched in 1994. But in PHP, there is a disadvantage i.e if we disable cookies (say in Facebook) the Facebook server will forget the person who has logged in previously and it will take to me that page when that application was launched for the first time. But in Java (JEE Edition, launched in 1999) we have
6 min read
How to get cookies from curl into a variable in PHP ?
The cURL standing for Client URL refers to a library for transferring data using various protocols supporting cookies, HTTP, FTP, IMAP, POP3, HTTPS (with SSL Certification), etc. This example will illustrate how to get cookies from a PHP cURL into a variable. The functions provide an option to set a callback that will be called for each response he
2 min read
ES6 Cookies
Cookies are basically a storage facility of web browsers. It comes under the Web Storage of a browser which is a local or client storage facility. The data are in the browser even after the browser window is closed in many websites there is need of remembering session information, such as, when we log in to email, Facebook, etc many time from the s
7 min read
How to set and unset cookies using jQuery?
An HTTP cookie is a small piece of data sent from a server and stored on client-side by the browser itself, Cookies are made to keep track of user and also to provide one nice browsing experience. We can also set our own cookies in the browser according to our need. Cookies can be set in the browser with the help of JavaScript or the jQuery. Here w
2 min read
Express.js req.cookies Property
The req.cookies property is used when the user is using cookie-parser middleware. This property is an object that contains cookies sent by the request. Syntax: req.cookies Parameter: No parameters. Return Value: Object Installation of the express module: You can visit the link to Install the express module. You can install this package by using thi
2 min read
Difference between req.cookies and req.signedCookies in Express.js
req.cookies: Request. Cookies are supposed to be cookies that come from the client (browser) and Response. Cookies are cookies that will send back to the client (browser). Cookies are small files/data that are sent to the client with a server request and stored on the client side. This helps us to keep track of the user’s actions. Cookie-parser is
3 min read
ASP Request.Cookies Collection
Basically Cookies are small files that are stored on a user’s computer. They are used to hold a modest amount of data specific to a particular client and website and can be accessed either by the web server or by the client computer. The Request.Cookies Collection is used for returning the value of the collection of the cookies. If the specified co
2 min read
ASP Response.Cookies Collection
Basically Cookies are small files which are stored on a user’s computer. It is used to hold a modest amount of data specific to a particular client and website and can be accessed either by the web server or by the client computer. The Response.Cookies Collection is used for setting the value of collection of the cookies.If the specified cookie doe
2 min read
jQWidgets jqxDocking cookies Property
jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxDocking is used for representing a widget to manage multiple windows and also the layout of a web page. Here each window in the specified jqxDocking can do mu
2 min read
What are some attributes that help to safeguard HTTP cookies from XSS attacks ?
What is HTTP cookies? HTTP cookies are generally known as internet/browser cookies. These cookies are commonly referred to as small blocks of data that are created by the web server at the time of a user is browsing a website. Cookies are placed on the user's device in a certain browsing session to provide some useful functionality to the user and
3 min read
In which location cookies are stored on the hard disk ?
Cookies: Cookies are small text files stored on a user's device by a website. They are used to store information about the user, such as preferences, login credentials, and shopping cart contents so that the website can retrieve that information during future visits. Cookies are often used for session management, to keep track of a user's session a
5 min read
Design a Cookies Message Popup Template using HTML and CSS
In this article, we will design a Cookies Message Popup template using HTML and CSS. Cookies play a pivotal role in enhancing user experiences on websites by storing information about user preferences and interactions. The "Cookies Message Popup Template" is a simple and customizable solution for websites to inform users about using cookies. Table
3 min read
JavaScript Cookies
JavaScript cookies are small data stored on a user's device by a web browser. These cookies play a crucial role in web development, enabling websites to store and retrieve information about user preferences, session states, and other data. Cookies facilitate a more personalized browsing experience by allowing websites to remember user actions and p
3 min read
Cookies in JavaScript
Cookies in JavaScript are small pieces of data stored on a user's browser by websites. They serve as a means to persistently store information between page visits. JavaScript, through the Document Object Model (DOM), can interact with cookies, enabling functionalities like user authentication, personalized content, and tracking user preferences. Co
1 min read
How to create Cookies Message Popup Template in Tailwind CSS ?
The popup informs users about the website's use of cookies and provides options for cookie preferences. The simple and functional cookie message Popup where users can either accept all cookies or customize their settings by clicking on the respective buttons. The Tailwind CSS classes are used to style various elements. These classes enable quick an
2 min read
How to Set & Retrieve Cookies using JavaScript ?
In JavaScript, setting and retrieving the cookies is an important task for assessing small pieces of data on a user's browser. This cookie can be useful for storing user preferences, session information, and many more tasks. Table of Content Using document.cookieUsing js-cookie libraryUsing document.cookieIn this approach, we are using the document
2 min read