req.cookies Property in Express.js


The req.cookies contains the cookies sent by the request while using the cookie-parser middleware. If the cookies are signed, please use the req.signedCookies property.

Syntax

req.cookies

Install the cookie-parser module −

npm install cookie-parser

Example 1

Create a file with the name "reqCookies.js" and copy the following code snippet. After creating the file, use the command "node reqCookies.js" to run this code as shown in the example below −

// req.cookies() Method Demo Example

// Importing the express & cookieParser module
var cookieParser = require('cookie-parser');
var express = require('express');

// Initializing the express and port number
var app = express();

// Initializing the router from express
var router = express.Router();
var PORT = 3000;

// Defining the cookieParser to be used
app.use(cookieParser());

// Defining an endpoint
app.get('/api', function (req, res) {
   req.cookies.title='TutorialsPoint';
   console.log(req.cookies);
   res.send();
});
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Hit the following Endpoint with a GET request − http://localhost:3000/api

Output

C:\home
ode>> node reqCookies.js Server listening on PORT 3000 [Object: null prototype] { title: 'TutorialsPoint' }

Example 2

Let's take a look at one more example.

// req.cookies() Method Demo Example

// Importing the express & cookieParser module
var cookieParser = require('cookie-parser');
var express = require('express');

// Initializing the express and port number
var app = express();

// Initializing the router from express
var router = express.Router();
var PORT = 3000;

// Defining the cookieParser to be used
app.use(cookieParser());

// Defining an endpoint
app.get('/api', function (req, res) {
   req.cookies.name='Mayank';
   req.cookies.age=21;
   console.log(req.cookies);
   res.send();
});
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Hit the following Endpoint with a GET Request − http://localhost:3000/api

Output

C:\home
ode>> node reqCookies.js Server listening on PORT 3000 [Object: null prototype] { title: 'Mayank', age: 21 }

Updated on: 29-Jan-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements