Creating and Sending Cookies in Node.js: A Step-by-Step Tutorial

Posted by

Node.js Cookies Tutorial: How to Create and Send Cookies in Node.js

Node.js Cookies Tutorial: How to Create and Send Cookies in Node.js

Node.js is a popular server-side platform for developing web applications. In this tutorial, we will learn how to create and send cookies in Node.js. Cookies are small pieces of data that are stored on the client’s computer by the web server. They are commonly used to store user preferences, such as language and theme settings, and to track user activity and sessions.

Creating Cookies in Node.js

To create a cookie in Node.js, we can use the built-in ‘response’ object to set the ‘Set-Cookie’ header. This header includes the name and value of the cookie, as well as optional attributes such as expiration date, domain, and path.


  const http = require('http');

  http.createServer((req, res) => {
    // Set a cookie with name 'username' and value 'john'
    res.setHeader('Set-Cookie', 'username=john');

    res.end('Cookie has been set');
  }).listen(3000);

Sending Cookies in Node.js

To send cookies in Node.js, we can access the ‘request’ object to retrieve the cookies sent by the client. We can then parse and use the cookies as needed.


  const http = require('http');

  http.createServer((req, res) => {
    // Retrieve and parse cookies from the 'Cookie' header
    const cookies = req.headers.cookie.split(';').reduce((acc, cookie) => {
      const [name, value] = cookie.trim().split('=');
      return { ...acc, [name]: value };
    }, {});

    res.end(`Hello ${cookies.username}`);
  }).listen(3000);

Now that we have learned how to create and send cookies in Node.js, we can use cookies to enhance the user experience on our web applications. Whether it’s storing user preferences or tracking user activity, cookies are a powerful tool for web developers.

Thank you for reading this Node.js cookies tutorial. I hope you found it helpful in understanding how to work with cookies in Node.js.

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@sandeepmishra1390
6 months ago

Continue make video bro..
Osam teaching .
And make rest API and one projects based on like real project of company