Open In App

Why are HTTP cookies used by Node.js for sending and receiving HTTP cookies?

Improve
Improve
Like Article
Like
Save
Share
Report

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 Structure

Filename: 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:



Last Updated : 06 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads