Why are HTTP cookies used by Node.js for sending and receiving HTTP cookies?
Last Updated :
06 Apr, 2023
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 maintain the past requests of any particular client to the server. It means we have to repeatedly authorize requests in order to move forward to the next page in a web application.
How do we overcome this problem?
What is a cookie?
A cookie in simpler terms is just textual information about some website. When you visit a particular website, some information is saved in your local system so that when you visit the same website again, this website is able to recognize you and show you the results according to your preferences. Cookies have been long used in internet history.
Example: When you visit a website you actually request the web page from the server. For a server, every request is a unique request. So if you visit a hundred times, the server will consider each and every request unique. Since the intensity of requests that arrive at a server is high, it is obvious and logical not to store all user information on the server. What if you never visit this website again? This information would be redundant. So, to uniquely remember you, the server sends the cookies along with the response which is saved in your local machine. Now the next time you hit the same server, you will get a response according to your preferences, as the server will recognize you.
This cookie is unique to every server (some exceptions exist today because of advertisements). So you might have many cookies in your system, but a server will recognize its own cookie and can analyze it for you.
HTTP Cookies: Using HTTP Cookies is one of the simple solutions to the problem. There are so many types of cookies used for smooth communication between the server and the client. The most commonly used cookie is a Session cookie.
Session cookies: These cookies are stored in temporary memory and valid up to the particular session till the user surfs on a particular website then the browser also provides us choose whether we want to store these cookies or not. Session cookies are mostly used in e-commerce websites in order to track our order list of items without session cookies our shopping cart will always empty after surfing a new page of a particular e-commerce website. That's why different HTTP cookies are used during surfing the internet in order to track our past requests.
How do Node.js Send and Receive cookies?
Express.js Framework uses middleware so that many requests can be handled easily. Similarly, Express.js supports the feature of parsing incoming requests using middleware. When a new client makes a request for authorization after successfully filling in the credentials, a response header containing signed cookies is sent to the client that contains all the information in the signed format, and a cookie is generated for the particular session on the client-side.
When the client makes a request for the second time, the request contains a signed cookie that has all the past accepted request information of that session. Node.js server parses this signed cookie using the signed key and checks whether the cookie is present for this session or not. If it exists, it accepts the incoming requests otherwise rejects all incoming requests.
Signed Cookie:
user=s%3Aadmin.MCnksbOc3nP5tXVflBq94MPEzyEd6yXYTwl9kT1as%2B0; Path=/; Domain=localhost;
Installing Modules: Install express and cookie-parser modules using the following command:
npm install express.js
npm install cookie-parser
Project Structure: It will look like the following:
Project StructureFilename: index.js
JavaScript
// Importing express module
const express = require("express");
// Importing cookie-parser module
const cookieParser = require('cookie-parser');
// Importing filesystem module
const fs = require("fs");
const path = require('path');
// Initialisation express server
const app = express();
// Parsing the signed cookies
app.use(cookieParser('1234567890GFG'));
function auth(req, res, next) {
console.log(req.signedCookies.user)
// Checking request containing signed
// cookies or not
if (!req.signedCookies.user) {
// Asking for authorization
let authHeader = req.headers.authorization;
if (!authHeader) {
var err = new Error('You are not authenticated!');
res.setHeader('WWW-Authenticate', 'Basic');
err.status = 401;
return next(err)
}
// Checking the credintials
let auth = new Buffer.from(authHeader.split(' ')[1],
'base64').toString().split(':');
// Username and Password
let user = auth[0];
let pass = auth[1];
if (user == 'admin' && pass == 'password') {
// Sending the set-cookie header to the client side
res.cookie("user", "admin", { signed: true })
// Authorized
next();
} else {
// Reject the authorization
let err = new Error('You are not authenticated!');
res.setHeader('WWW-Authenticate', 'Basic');
err.status = 401;
return next(err);
}
}
else {
// Checking whether the signed cookie exist or not
if (req.signedCookies.user === "admin") {
// Allowing for handling incoming request
next()
}
// Rejects all the incoming requests.
else {
let err = new Error('You are not authenticated!');
err.status = 401;
return next(err);
}
}
}
// Handling authorization
app.use(auth);
app.use(express.static(path.join(__dirname, 'public')));
// Listening the server
app.listen((3000), () => {
console.log("Server is Running ");
})
Run the index.js file using the following 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 mentioned in the code.

- If the entered username and password match the condition, then the mentioned location index.html will render on the browser as shown below:

Response Header by the server:

Generated cookies on the client side:

Similar Reads
How to Set, View and Manipulate Cookies using 'Response.cookie()' and Postman ?
Cookies enable websites to store small pieces of information on a user's device. It helps enhance user experience and enable various functionalities. In this article, we'll explore a simple way to manipulate cookies using the 'Response.cookie()' functionPrerequisite:Basics of NodejsBasics of Express
2 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 I
5 min read
Firebase (sign in with Google) Authentication in Node.js using Firebase UI and Cookie Sessions
Firebase Authentication provides the backend services that are easy-to-use SDKs and ready-made UI libraries to authenticate users to your app. Prerequisites: Basic knowledge of node, JavaScript and firebase. Setup: First we need to create a Firebase Project, head over to firebase Console and create
4 min read
How to serialize a cookie name-value pair into a Set-Cookie header string in JavaScript ?
In this article, you will understand to serialize a cookie with name and value into a Set-Cookie header string. Basically, here we are trying to pass the cookie with a compatible set-cookie string format. Cookie: Cookies are small blocks of data created by a web server while a user is browsing a web
2 min read
How to parse HTTP Cookie header and return an object of all cookie name-value pairs in JavaScript ?
To parse HTTP Cookie header we will spilt the cookies data and create objects from the key-value extracted from cookies. Cookies are simply small text files that a web server sends to the user's browser. They contain the following data. Name-value pair with actual data.The expiry date for when the c
3 min read
What are the differences between HTTP module and Express.js module ?
HTTP and Express both are used in NodeJS for development. In this article, we'll go through HTTP and express modules separatelyHTTP: It is an in-build module which is pre-installed along with NodeJS. It is used to create server and set up connections. Using this connection, data sending and receivin
2 min read
How to Send Response From Server to Client using Node.js and Express.js ?
In web development, sending responses from the server to the client is a fundamental aspect of building interactive and dynamic applications. Express.js, a popular framework for Node.js, simplifies this process, making it easy to send various types of responses such as HTML, JSON, files, and more. T
4 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
How to manipulate cookies by using âResponse.cookie()â in Express?
Cookies are small data that is stored on the client's computer. Using this cookie various tasks like authentication, session management, etc can be done. In Express JS we can use the cookie-parser middleware to manage the cookies in the application. In this article, we going to manipulate cookies in
3 min read
Different types of module used for performing HTTP Request and Response in Node.js
HTTP's requests and responses are the main fundamental block of the World Wide Web. There are many approaches to perform an HTTP request and Response in Node.js. Various open-source libraries are also available for performing any kind of HTTP request and Response. An HTTP request is meant to either
3 min read