Skip to content
doubtly

2 answers

Cookies are simple, small files/data that are sent to the client with a server

request and stored on the client side. Every time the user loads the website back, this cookie is sent with the request. This helps us keep track of the user’s actions.

The following are the numerous uses of HTTP Cookies −

Session management

Personalization(Recommendation systems)

User tracking

To use cookies with Express, we need the cookie-parser middleware. To

install it, use the following code −

npm install --save cookie-parser

Now to use cookies with Express, we will require the cookie-parser package.

cookie-parser looks at the headers in between the client and the server transactions, reads these headers, parses out the cookies being sent, and saves them in a browser. In other words, cookie-parser will help us create and manage cookies depending on the request a user

makes to the server.

Doubtly · 19 Nov 2023 Report
Was this answer helpful?

A cookie is a small piece of data the server asks the browser to store; the browser sends it back with every later request to that site. In Express, cookies are set with res.cookie(), read with req.cookies (after the cookie-parser middleware) and removed with res.clearCookie().

Uses: session management (login), personalisation (theme, language), and tracking user activity.

Step 1: install and add the middleware

npm install express cookie-parser

Step 2: set, read and clear cookies

const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
app.use(cookieParser());

// set a cookie
app.get('/set', (req, res) => {
  res.cookie('name', 'Rahul', { maxAge: 60000, httpOnly: true });
  res.send('Cookie set');
});

// read cookies
app.get('/get', (req, res) => {
  res.send(req.cookies);   // { name: 'Rahul' }
});

// delete a cookie
app.get('/clear', (req, res) => {
  res.clearCookie('name');
  res.send('Cookie cleared');
});

app.listen(3000);

res.cookie() adds a Set-Cookie header to the response, so the browser stores it. cookie-parser only reads the Cookie header of incoming requests and fills req.cookies. Options such as maxAge/expires control lifetime, httpOnly hides the cookie from client-side JavaScript, and secure sends it only over HTTPS.

Doubtly AI · 24 Oct 2026 AI-verified · Oct 2026 Report
Was this answer helpful?

Your answer

Log in or create a free account to answer this question.