How can I set cookie in node js using express framework?

To set a cookie in Node.js using the Express framework, you can follow these steps:

  1. First, make sure you have the Express framework installed in your project. You can install it by running the following command in your project directory:
npm install express
  1. In your Node.js file, require the Express module and create an instance of the Express application:
const express = require('express');
const app = express();
  1. To set a cookie, you can use the res.cookie() method provided by Express. This method takes two or more arguments: the name of the cookie and its value. You can also provide additional options as an optional third argument, such as the expiration date, domain, and path. Here's an example of setting a cookie named "myCookie" with the value "hello":
app.get('/set-cookie', (req, res) => {
  res.cookie('myCookie', 'hello');
  res.send('Cookie has been set');
});
  1. Finally, start the server and listen for incoming requests:
app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

Now, when you make a GET request to the "/set-cookie" endpoint, the server will set a cookie named "myCookie" with the value "hello" in the response. You can verify this by checking the cookies in the browser's developer tools.

Note: Remember to replace "/set-cookie" with the desired endpoint path and customize the cookie name, value, and options according to your requirements.

This is how you can set a cookie in Node.js using the Express framework. Let me know if you have any further questions.