Session Cookies in Node.js
Last Updated :
07 Oct, 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:
Similar Reads
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
5 min read
How to Manage Sessions and Cookies in Express JS? Express is a small framework that sits on top of NodeJS web server functionality to simplify its APIs and add helpful new features. It makes it easier to organize your applicationâs functionality with middleware and routing. It adds helpful utilities to NodeJS HTTP objects, it helps the rendering of
4 min read
Disabling Sessions in Passport.js Passport.js is a popular authentication middleware for Node.js, which offers a range of strategies to authenticate users. By default, Passport.js uses sessions to maintain a user authentication state across requests. However, in some scenarios, you may want to disable session management for various
5 min read
How to Access HTTP Cookie in Node.js ? Cookies are small pieces of data sent by a server and stored on the client side, typically in the user's browser. They are often used to maintain stateful information such as user sessions, preferences, or tracking data. In Node.js, accessing and managing cookies is a common requirement for building
3 min read
Essence of Node.js Node.js or Node has a small core group of modules, commonly referred to as the Node Core that is exposed as the public Node API by using we write our applications or we can say that the Node Core implements the public Node API. Some examples of the modules present in the node core are: To work with
8 min read