Cookies are small data that are stored on a client side and sent to the client along with server requests. Cookies have various functionality, they can be used for maintaining sessions and adding user-specific features in your web app. For this, we will use cookie-parser module of npm which provides middleware for parsing of cookies.
First set your directory of the command prompt to root folder of the project and run the following command:
npm init
This will ask you details about your app and finally will create a package.json file.
After that run the following command and it will install the required module and add them in your package.json file
npm install express cookie-parser --save
package.json file looks like this :

After that we will setup basic express app by writing following code in our app.js file in root directory .
let express = require( 'express' );
let app = express()
app.get( '/' , (req, res)=>{
res.send( 'welcome to express app' );
});
app.listen(3000, (err)=>{
if (err)
throw err;
console.log( 'listening on port 3000' );
});
|
After that if we run the command
node app.js
It will start our server on port 3000 and if go to the url: localhost:3000, we will get a page showing the message :
welcome to express app
Here is screenshot of localhost:3000 page after starting the server :

So until now we have successfully set up our express app now let’s start with cookies.
For cookies first, we need to import the module in our app.js file and use it like other middlewares.
var cookieParser = require('cookie-parser');
app.use(cookieParser());
Let’s say we have a user and we want to add that user data in the cookie then we have to add that cookie to the response using the following code :
res.cookie(name_of_cookie, value_of_cookie);
This can be explained by the following example :
let express = require( 'express' );
let cookieParser = require( 'cookie-parser' );
let app = express()
app.use(cookieParser());
app.get( '/' , (req, res)=>{
res.send( 'welcome to express app' );
});
let users = {
name : "Ritik" ,
Age : "18"
}
app.get( '/setuser' , (req, res)=>{
res.cookie( "userData" , users);
res.send( 'user data added to cookie' );
});
app.get( '/getuser' , (req, res)=>{
res.send(req.cookies);
});
app.listen(3000, (err)=>{
if (err)
throw err;
console.log( 'listening on port 3000' );
});
|
So if we restart our server and make a get request to the route: localhost:3000/getuser before setting the cookies it is as follows :

After making a request to localhost:3000/setuser it will add user data to cookie and gives output as follows :

Now if we again make a request to localhost:3000/getuser as this route is iterating user data from cookies using req.cookies so output will be as follows :

If we have multiple objects pushed in cookies then we can access specific cookie using req.cookie.cookie_name .
Adding Cookie with expiration Time
We can add a cookie with some expiration time i.e. after that time cookies will be destroyed automatically. For this, we need to pass an extra property to the res.cookie object while setting the cookies.
It can be done by using any of the two ways :
//Expires after 400000 ms from the time it is set.
res.cookie(cookie_name, 'value', {expire: 400000 + Date.now()});
//It also expires after 400000 ms from the time it is set.
res.cookie(cookie_name, 'value', {maxAge: 360000});
Destroy the cookies :
We can destroy cookies using following code :
res.clearCookie(cookieName);
Now let us make a logout route which will destroy user data from the cookie. Now our app.js looks like :
let express = require( 'express' );
let cookieParser = require( 'cookie-parser' );
let app = express()
app.use(cookieParser());
app.get( '/' , (req, res)=>{
res.send( 'welcome to express app' );
});
let users = {
name : "Ritik" ,
Age : "18"
}
app.get( '/setuser' , (req, res)=>{
res.cookie( "userData" , users);
res.send( 'user data added to cookie' );
});
app.get( '/getuser' , (req, res)=>{
res.send(req.cookies);
});
app.get( '/logout' , (req, res)=>{
res.clearCookie( 'userData' );
res.send( 'user logout successfully' );
});
app.listen(3000, (err)=>{
if (err)
throw err;
console.log( 'listening on port 3000' );
});
|
For destroying the cookie make get request to following link: user logged out[/caption]
To check whether cookies are destroyed or not make a get request to localhost:3000/getuserand you will get an empty user cookie object.

This is about basic use of HTTP cookies using cookie-parser middleware. Cookies can be used in many ways like maintaining sessions and providing each user a different view of the website based on their previous transactions on the website.
Similar Reads
HTTPS in Node.js
HTTP: When the data is transferred in HTTP protocol it just travels in the clear text format. HTTPS: It simply encrypts the request from the browser to the web server, so it is tough to sniff that information. It basically works on two things: SSL (Secure Socket Layer)TLS (Transport layer security)
3 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
Express vs Hapi in Node.js
'Express' Module: In order to use the express module, we need to install the NPM (Node Package Manager) and the following modules (on cmd). // Creates package.json file >> npm init // Installs express module >> npm install express --save // OR >> npm i express -s Import express mod
3 min read
Node.js http.ClientRequest.end() API
The http.ClientRequest.end() is an inbuilt application programming interface of class ClientRequest within http module which is used to finish sending the request. If any parts of the body are unsent. Syntax: const request.end([data[, encoding]][, callback]) Parameters: This method takes the data as
2 min read
Node.js http.ClientRequest.host API
The http.ClientRequest.host is an inbuilt API : Application Programming Interface of class ClientRequest within http module which is used to get the object of client request host. Syntax: const request.host Parameters: This API does not accept any argument as parameter. Return Value : This method re
1 min read
Node.js http.server.close() Method
The http.server.close() is an inbuilt application programming interface of class Server within the HTTP module which is used to stop the server from accepting new connections. Syntax: const server.close([callback])Parameters: This method accepts only one optional callback function argument as a para
2 min read
Node.js HTTP Module
In NodeJS, the HTTP module is a core built-in module that enables developers to create and manage HTTP servers. It plays a crucial role in handling server-side HTTP requests and responses, allowing for seamless communication between clients and servers. In this article, we will dive into the NodeJS
6 min read
Node.js https.request() Function
Https request function in Node is used to make the http request over secure http or https. It provide more control to the request like setting headers, http methods, adding request data and handle the responses. https.request(options, callback)It is a part of https module and allows to send differen
2 min read
Node.js http.ClientRequest.method API
The http.ClientRequest.method is an inbuilt application programming interface of class ClientRequest within http module which is used to get the object of client request method. Syntax: const request.method Parameters: This API does not accept any argument as parameter. Return Value : This method re
1 min read
Node.js http.IncomingMessage.complete Method
The http.IncomingMessage.complete is an inbuilt application programming interface of class IncomingMessage within http module which is used to check if a complete HTTP message has been received and successfully parsed or not. Syntax: const message.complete Parameters: This method does not accept any
2 min read