res.cookie() Method in Express.js


The res.cookie() method is used for setting the cookie name to value. The value parameter can be a string or an object converted to JSON.

Syntax

res.cookie( name, value, [options] )

Parameters

The options parameter can have the following values −

  • domain − It represents the domain name of the cookie. Default refers to the domain name of the app.

  • encode − This parameter is used for encoding the cookie values in an asynchronous function.

  • expires − This parameter defines the expiry time of the cookie in GMT format. Default value is 0, that creates a session cookie.

  • httpOnly − This Boolean parameter flags the cookie to be only used by the web server.

  • maxAge − This parameter represents a convenient option for setting the expiry time relative to the current time in milliseconds.

  • path − This is the path where cookie will be stored. Default is "/".

  • secure − This marks the cookie to be used only with https.

  • signed − This indicates if the cookie should be signed or not.

Example

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

// res.cookie(name, value, [options]) Method Demo Example

// Importing the express module
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 an endpoint
app.get('/api', function(req, res){
   // Setting the below key-value pair
   res.cookie('name', 'tutorialsPoint');
   res.send("Cookies are set");
});
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 resCookie.js Server listening on PORT 3000 Cookies are set

Updated on: 29-Jan-2022

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements