Cookie and how to create with detail code explaination in Nodejs
Tags: webdev, node, backend, javascript
Published: 2023-06-29 15:32:22

A cookie is a small piece of data that is stored on the client-side (in the user's browser) and sent back to the server with every HTTP request. Cookies are commonly used for session management, user preferences, and tracking.


1. Set up the project:
   - Create a new directory for your project and navigate to it.
   - Initialize a new Node.js project and install the required dependencies:
     ```bash
     npm init -y
     npm install express
     ```

2. Create a `server.js` file and set up the basic Express server:
   ```javascript
   const express = require('express');
   const app = express();
   const port = 3000;

   // Middleware for parsing JSON requests
   app.use(express.json());

   // Endpoint for setting a cookie
   app.get('/set-cookie', (req, res) => {
     res.cookie('myCookie', 'example value', { maxAge: 900000, httpOnly: true });
     res.send('Cookie set successfully');
   });

   // Start the server
   app.listen(port, () => {
     console.log(`Server listening on port ${port}`);
   });
   ```

3. Start the server:
   - Run `node server.js` in the command line to start the server.

4. Testing the cookie:
   - Access `http://localhost:3000/set-cookie` in a web browser or using an API testing tool like Postman.
   - After accessing the endpoint, the server will respond with the message "Cookie set successfully" and set a cookie named "myCookie" with the value "example value".

Let's break down the relevant code:

- `res.cookie('myCookie', 'example value', { maxAge: 900000, httpOnly: true })`: This line sets the cookie named "myCookie" with the value "example value". The `maxAge` option sets the expiration time of the cookie in milliseconds (in this example, it expires after 900,000 milliseconds, or 15 minutes). The `httpOnly` option makes the cookie accessible only through HTTP requests and not through client-side JavaScript, enhancing security.

- `res.send('Cookie set successfully')`: This line sends a response to the client with the message "Cookie set successfully" indicating that the cookie was set.

By setting a cookie in the response, the client's browser will receive and store the cookie, associating it with the domain of the server. On subsequent requests to the same domain, the browser will automatically include the cookie in the request headers, allowing the server to access the cookie data.



In addition to `maxAge` and `httpOnly`, there are several other parameters that can be passed as options when setting a cookie using the `res.cookie()` method. Here are some commonly used options:

- `domain`: Specifies the domain associated with the cookie. By default, the cookie is associated with the domain of the current page. You can set a specific domain to limit the cookie's scope.

- `path`: Sets the path on the server where the cookie is valid. By default, the cookie is valid for all paths. You can specify a specific path to restrict the cookie's availability to certain routes.

- `secure`: When set to `true`, the cookie is only sent over HTTPS connections. It ensures that the cookie is transmitted securely. Note that you typically want to use this option in production environments.

- `sameSite`: Specifies the SameSite attribute of the cookie, which determines whether the cookie is sent with cross-site requests. It can be set to `true`, `false`, or `'strict'`. Setting it to `'strict'` ensures the cookie is only sent with requests from the same site. This helps protect against certain types of cross-site request forgery (CSRF) attacks.

- `expires`: Sets an explicit expiration date for the cookie. It accepts a `Date` object or a string representing a date in the GMT format. If both `maxAge` and `expires` are set, `expires` takes precedence.

- `secureProxy`: When set to `true`, the cookie is only sent over secure connections (HTTPS) when using a reverse proxy. It is useful when your server is behind a proxy that handles SSL termination.

- `signed`: When set to `true`, the cookie value will be signed using the `secret` provided in `req.secret`. This adds a signature to the cookie to verify its integrity when received back from the client.

These are just a few of the available options for setting cookies. You can refer to the Express.js documentation for the `res.cookie()` method to explore additional options and their functionalities.

Remember to choose the appropriate options based on your specific requirements, taking into account security considerations and the desired behavior of the cookie.