- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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