Express res.cookie() Function
Last Updated :
15 Jan, 2024
The res.cookie() function is used to set the cookie name to value. The value parameter may be a string or object converted to JSON.
Syntax:
res.cookie(name, value [, options])
Parameters: The name parameter holds the name of the cookie and the value parameter is the value assigned to the cookie name. The options parameter contains various properties like encode, expires, domain, etc.Â
Return Value: It returns an Object.Â
Steps to create the application:
Step 1: You can install this package by using this command.
npm install express
Step 2: After installing the express module, you can check your express version in the command prompt using the command.
npm version express
Project Structure:
The updated dependencies in package.json file will look like:
"dependencies": {
"express": "^4.18.2",
}
Example 1: Below is the code example of the res.cookie() Function.
Javascript
const express = require( 'express' );
const app = express();
const PORT = 3000;
app.get( '/' , function (req, res) {
res.cookie( 'name' , 'geeksforgeeks' );
res.send( "Cookie Set" );
});
app.listen(PORT, function (err) {
if (err) console.log(err);
console.log( "Server listening on PORT" , PORT);
});
|
Steps to run the program:
node index.js
Output:
Server listening on PORT 3000
Example 2: Below is the code example of the res.cookie() Function.
Javascript
const express = require( 'express' );
const app = express();
const PORT = 3000;
app.use( '/' , function (req, res, next) {
res.cookie( 'title' , 'GeeksforGeeks' );
res.send( "Cookie Set" );
next();
})
app.get( '/' , function (req, res) {
console.log( 'Cookie SET' );
});
app.listen(PORT, function (err) {
if (err) console.log(err);
console.log( "Server listening on PORT" , PORT);
});
|
Steps to run the program:
Run the index.js file using the below command:
node index.js
Output: go to http://localhost:3000/ you will see the output:
Server listening on PORT 3000
Cookie SET
We have a complete list of Express Response methods, properties and events, to check those please go through this Express Response Complete Reference article.
Share your thoughts in the comments
Please Login to comment...