How to set cookie on server side using nodejs?

To set a cookie on the server side using Node.js, you can make use of the Set-Cookie HTTP header. Here's an example of how you can set a cookie in a Node.js server:

const http = require('http');

const server = http.createServer((req, res) => {
  // Set the cookie
  res.setHeader('Set-Cookie', 'cookieName=cookieValue; Path=/;');

  // Send a response
  res.statusCode = 200;
  res.end('Cookie set successfully');
});

server.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

 

In the above example, the server sets a cookie named cookieName with the value cookieValue. The Set-Cookie header is set using the setHeader method of the response (res) object. The cookie is then sent in the HTTP response to the client.

The cookie is set with the Path=/; attribute, which means that the cookie is valid for all paths on the website. You can modify the Path attribute according to your needs. Additionally, you can set other attributes such as Expires, Max-Age, Domain, etc., depending on your requirements. You can refer to the documentation of the Set-Cookie header for more details on available options.

Remember to adapt the server code according to your specific needs and the framework or libraries you are using, as the above example demonstrates a basic HTTP server using the built-in http module in Node.js.