Skip to content
Related Articles

Related Articles

Why HTTP cookies used and Sending/Receiving HTTP cookies using Node.js ?
  • Difficulty Level : Expert
  • Last Updated : 18 Jan, 2021

HTTP Protocol is one of the most important protocols of the Application layer of the OSI model. The main use of this protocol to sending hypertext information to the client to the server and server to the client to communicate between them on the World Wide Web but the HTTP protocol is a 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?

What is a cookie?
A cookie in simpler terms means just the 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 and have developed in a magnificent way. 

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 every user’s information on the server. Maybe you never visit again and the same information will 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 you 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 surfing on a particular website then the browser also provides us choose whether we want to store these cookies or not. Session cookies 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 used during surfing on the internet in order to track our past requests.

How Node.js Send and Receive cookies?

Express.js Framework uses lots of middleware so that many kinds of different requests can be handled easily. Similarly, Express.js supports the feature of parsing the incoming requests using middleware. When a new client makes a request for authorization after successfully filling the credentials. A response header containing signed cookies send 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 second time client makes a request. The request contains a signed cookie that contains all the past accepted requests information of that session. Node.js server parse the signed cookie using the signed key and check whether the cookie is present for this session or not. If exits, 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 module using the following command:

npm install express.js
npm install cookie-parser

Project Structure: It will look like the following:

Project Structure

Filename: index.js


// Importing express module
const express = require("express");
// Importing cookie-parser module 
var cookieParser = require('cookie-parser');
// Importing filesystem module
const fs = require("fs");
var path = require('path');
// Intialisation express server
const app = express();
// Parsing the signed cookies
function auth(req, res, next) {
    // Checking request containing signed
    //  cookies or not 
    if (!req.signedCookies.user) {
        // Asking for authorization
        var 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
        var auth = new Buffer.from(authHeader.split(' ')[1],
        // Username and Password
        var user = auth[0];
        var pass = auth[1];
        if (user == 'admin' && pass == 'password') {
            // Sending the set-cookie header to the client side
            res.cookie("user", "admin", { signed: true })
            // Authorized 
        } else {
            // Reject the authorization
            var 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
        // Rejects all the incoming requests.
        else {
            var err = new Error('You are not authenticated!');
            err.status = 401;
            return next(err);
// Handling authorization
app.use(express.static(path.join(__dirname, 'public')));
// Listening the server
app.listen((3000), () => {
    console.log("Server is Running ");

Run 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 mention in the code.

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

Response Header by the server:

Generated cookies on the client-side:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :