Open In App

How to access HTTP Cookie in Node.js ?

Improve
Improve
Like Article
Like
Save
Share
Report

Cookies are small data that are stored on the client side and sent to the client along with server requests. With the help of the cookie-parser module, we can set the cookies as well as get the cookies. 

Create a project folder and run the following command from the root directory of the project:

npm init -y

This command will ask for the name of the module. Keep pressing enter until the end of the options. This will create an empty npm module with a package.json file. We will now install all the required dependencies using the below command:

npm install express cookie-parser

We are using express to create a server and cookie-parser is the library which will help us in working with cookies easily. Let’s create a file called index.js and write the code to create a server with two routes to set and get the cookies as given in the code below:

Filename: index.js

Javascript




// Requiring modules
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
 
// cookieParser middleware
app.use(cookieParser());
 
// Route for setting the cookies
app.get('/setcookie', function (req, res) {
 
    // Setting a cookie with key 'my_cookie'
    // and value 'geeksforgeeks'
    res.cookie('my_cookie', 'geeksforgeeks');
    res.send('Cookies added');
})
 
// Route for getting all the cookies
app.get('/getcookie', function (req, res) {
    res.send(req.cookies);
})
 
// Server listens to port 3000
app.listen(3000, (err) => {
    if (err) throw err;
    console.log('server running on port 3000');
});


Here we have a route /setcookie which is used to set a cookie with key my_cookie and the value as geeksforgeeks. We can alter these keys and values to be anything as per requirement. Another route is /getcookie which is used to get all the cookies and show them on the webpage. At the end of the code, we are listening to 3000 ports for our server to be able to run.

Run the index.js file using the following command:

node index.js

This will run the server as shown in the image above. We can check cookies by visiting localhost:3000/setcookie.

This will show a message as cookies are added. We can check the cookies by visiting localhost:3000/getcookie.

Now we can see that our cookies are added to the cookies object as shown above.


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