HTTP Cookies in Node.js


The cookies are the data stored in the user’s browser for quick access. For example, whenever we log in to any website, the server returns the access token, which can be stored in the browser’s cookie with the expiry time. So, whenever a user revisits the website, they don’t need to log in to the website repeatedly if the access token stored in the cookies has not expired.

We can also access the browser’s cookies on the server side in NodeJS. After that, we can check if any detailed data exists in the cookies we are looking at, and if not, we can set that data into cookies again.

Here, we will learn to access, set, and clear the cookies using NodeJS.

Syntax

Users can follow the syntax below to set and get the cookies using NodeJS.

app.get("/", (req, res) => {
   res.cookie("name", value);
});

app.get("/", (req, res) => {
   res.send(req.cookies);
});

In the above syntax, we set the cookies in the first route using the ‘res.cookie()’ method and get the cookie using the ‘req.cookies’ in the second route.

Before users start trying the example below, they should have created the Node application. Also, execute the below commands to install the app's ‘express’ and ‘cookie-parser’ NPM packages.

npm i express cookie-parser

Example

In the example below, we have created the basic server using express. Also, we have used the ‘cookieParse’ in the express app.

We show the welcome message whenever users go on the home route after running the application. Also, we have created the car object containing some properties.

Whenever the user goes to the ‘setcookies’ route, it sets the car data in the cookies. Users can go to the ‘getcookies’ route to access all cookies. Users can go on the ‘clear’ route to clear the cookies.

let express = require("express");
let cookieParser = require("cookie-parser");
//setup express app
let app = express();

app.use(cookieParser());

//basic route for homepage
app.get("/", (req, res) => {
   res.send("Express app is created successfully, and you are on homepage");
});

// create a JSON object to store car data
let car = {
   name: "BMW",
   model: "X5",
   price: 50000,
};

// route to set car object as cookie
app.get("/setcar", (req, res) => {
   res.cookie("carData", car);
   res.send("car data is stored in cookies");
});

// route to get car object from cookies
app.get("/getcar", (req, res) => {
   res.send(req.cookies);
});

// route to clear car object from cookies
app.get("/clear", (req, res) => {
   res.clearCookie("carData");
   res.send("Cookies are cleared!");
});

//server listens to port 3000
app.listen(8000, (err) => {
   if (err) throw err;
   console.log("listening on port 8000");
});

Output

Example 2

In the example below, we set the cookies with the expiry time. We have created the table and homeWindow object containing the various properties in the key-value pair.

We can set both objects with different expiry times by making a get request on the ‘setCookies’ route. Also, users can access and delete particular cookies by passing the name as a parameter. In the output, users can observe that we accessed only table objects.

let express = require("express");
let cookieParser = require("cookie-parser");
//setup express app
let app = express();

app.use(cookieParser());

//basic route for homepage
app.get("/", (req, res) => {
   res.send("Express app is created successfully, and you are on homepage");
});

let table = {
   color: "brown",
   material: "wood",
   size: "small",
   price: 100,
};
let homeWindow = {
   color: "white",
   material: "glass",
   size: "big",
   price: 200,
};

// set cookies for table and homeWindow with different expiry time
app.get("/setCookies", (req, res) => {
   res.cookie("table", table, { maxAge: 900000, httpOnly: true });
   res.cookie("homeWindow", homeWindow, { maxAge: 600000, httpOnly: true });
   res.send("Cookies are set with different expiry time");
});

// get cookies
app.get("/getCookies", (req, res) => {
   res.send(req.cookies);
});

// get cookies with specific name
app.get("/getCookies/:name", (req, res) => {
   res.send(req.cookies[req.params.name]);
});

// delete cookies with specific name
app.get("/deleteCookies/:name", (req, res) => {
   res.clearCookie(req.params.name);
   res.send("Cookies with name " + req.params.name + " is deleted");
});

//server listens to port 3000
app.listen(8000, (err) => {
   if (err) throw err;
   console.log("listening on port 8000");
});

Output

Users learned to set and get cookies from NodeJS. We use the res.cookie() method to set cookies and req.cookies to get cookies. Also, we can use the res.clearCookies() method to clear any particular or all cookies.

Updated on: 06-Apr-2023

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements