set cookie in node

To set a cookie in Node.js, you can follow these steps:

  1. Import the http module: Start by importing the built-in http module in your Node.js file. This module provides the functionality to create an HTTP server and handle incoming requests.

  2. Create an HTTP server: Use the createServer() method from the http module to create an instance of an HTTP server. This method takes a callback function as a parameter, which will be executed whenever a request is received.

  3. Handle the request: Inside the callback function, use the request and response objects to handle the incoming request and send a response back to the client. The request object contains information about the incoming request, such as the headers and URL. The response object is used to send a response back to the client.

  4. Set the cookie: To set a cookie, you need to add a Set-Cookie header to the response object. This header contains the name and value of the cookie. You can use the response.setHeader() method to set the header.

Example: response.setHeader('Set-Cookie', 'myCookie=myValue');

Note: You can also specify additional options for the cookie, such as the expiration date, domain, and path. These options can be added as additional parameters to the Set-Cookie header.

  1. Send the response: After setting the cookie, use the response.end() method to send the response back to the client. This method takes an optional parameter, which is the content of the response. If you don't need to send any content, you can omit this parameter.

  2. Start the server: Finally, use the server.listen() method to start the server and make it listen for incoming requests on a specific port.

Example: server.listen(3000);

Note: Replace 3000 with the desired port number.

That's it! By following these steps, you can set a cookie in Node.js. Remember to adapt the code according to your specific requirements.