Cookies in Depth using Javascript and NodeJs
Tags: cookies, javascript, node, webdev
Published: 2024-03-22 08:13:02

## What are Cookies?

Cookies are small pieces of data stored on a user's web browser. They are used to remember stateful information (such as items added in the shopping cart in an online store) or to record the user's browsing activity (like recording which pages were visited in the past). There are different types of cookies:

**Session cookies**: Temporary cookies that expire once you close your browser. They are used to track user activity during a single session like e-com websites use session cookies to track users' shopping cart items as they browse different pages of the site.

**Persistent cookies**: These remain on your device for a set period specified in the cookie. They are used to remember your preferences like news websites use persistent cookies to store preferred language, region, or layout settings.

**Third-party cookies**: Placed by a website other than the one you are currently visiting, these are often used for advertising and tracking across multiple websites. Ever searched for Ipad on Amazon and started seeing ads on other websites? That's third party cookies


## Why are Cookies Useful?



- **Session management**: They help manage user sessions, allowing websites to recognize users and their preferences as they navigate through the site. This includes keeping users logged in, tracking their progress through a site, and storing items in a shopping cart.

- **Personalization**: Cookies store user preferences and settings to customize the user experience on a website. This can include language settings, themes, and other personalization details.

- **Tracking and analytics**: Websites use cookies to gather data about user behavior, such as the pages visited, time spent on the site, and interaction with content. This information helps website owners understand how users interact with their site, allowing for improvements and more targeted content or advertisements.

- **Advertising**: Cookies are used to deliver targeted advertisements to users based on their browsing history and preferences. They help advertisers show relevant ads to users and track the performance of ad campaigns.

## Implementing Cookies

Cookies can be implemented on both client and server side.

### Client Side (Javascript)

**Creating Cookie**: To create a cookie, you assign a string to document.cookie that contains the cookie name, value, and optionally other attributes like expiration, path, domain, secure, and SameSite. For example:

```javascript
document.cookie = "username=JohnDoe; expires=Thu, 31 Dec 2029 23:59:59 GMT; path=/";
```

This line creates a cookie named username with the value JohnDoe that expires on December 31, 2029, and is accessible to all pages within the domain.

**Reading Cookie**: To read cookies, you access the document.cookie property, which returns all cookies for the current domain as a string. You then need to parse this string to find the value of the specific cookie you are interested in. For example:

```javascript
var cookieValue = document.cookie
  .split('; ')
  .find(row => row.startsWith('username='))
  ?.split('=')[1];
```

This code snippet finds the username cookie and retrieves its value.

### Server Side (Node.js)

**Setup**: In your project, create a file named server.js (or another name of your choice) and install basic Express server, along with cookie-parser library to handle cookies easily

```bash
npm install express cookie-parser
```

Then, you can use it in your Express application to read and set cookies.

```javascript

// Import the required modules
const express = require('express');
const cookieParser = require('cookie-parser');

// Initialize the express application
const app = express();

// Use the cookie-parser middleware
app.use(cookieParser());

// Route to set a cookie
app.get('/set-cookie', (req, res) => {
    // Set a cookie named 'user' with a value of 'John Doe'
    res.cookie('user', 'John Doe', { maxAge: 900000, httpOnly: true });
    res.send('Cookie has been set');
});

// Route to get the cookie value
app.get('/get-cookie', (req, res) => {
    // Access the cookie named 'user'
    let userCookie = req.cookies.user;
    if (userCookie) {
        res.send(`Cookie value: ${userCookie}`);
    } else {
        res.send('No cookie found');
    }
});

// Start the server
const PORT = 3000;
app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});
```

In this example:

- The /set-cookie route sets a cookie named user with the value John Doe.
- The /get-cookie route reads the value of the user cookie and sends it in the response.
- The cookie-parser middleware is used to parse the cookies attached to the client request object.

Run your server using the command node server.js, and then visit http://localhost:3000/set-cookie in your browser to set the cookie, and http://localhost:3000/get-cookie to retrieve and display the cookie value.

## Cookies vs Local Storage

Cookies and local storage are both used to store data on the client's side in web applications, but they serve different purposes and have different characteristics:

**Storage Size**: Local storage can hold more data compared to cookies.

**Lifespan**: Cookies can be set to expire; local storage data stays until it is cleared.

**Server Interaction**: Cookies are sent with every request to the server, whereas local storage data stays on the client-side.

**Scope**: Cookies are accessible by both client and server; local storage is strictly client-side.

In summary, cookies are better suited for smaller amounts of data that need to be sent to the server with each request, while local storage is more appropriate for storing larger amounts of data that don’t need to be sent to the server and should persist beyond the session.

## Be Careful

When maintaining cookies, there are several important points to consider to ensure security, privacy, and a good user experience:

- **Security**:

-- Use the Secure attribute to ensure cookies are sent over HTTPS, protecting them from being intercepted during transmission.

-- Set the HttpOnly attribute to prevent client-side scripts from accessing the cookie, reducing the risk of cross-site scripting (XSS) attacks.

-- Consider using the SameSite attribute to control how cookies are sent with cross-site requests, which can help prevent cross-site request forgery (CSRF) attacks.


- **Privacy and Compliance**:

-- Privacy laws and regulations, such as the General Data Protection Regulation (GDPR) in the EU, require obtaining consent from users before storing cookies that track information.

-- Offer users the ability to choose which cookies they want to allow (e.g., essential, analytics, marketing) and provide an easy way to change their preferences.

- **Expiration and Management**:

-- Set an appropriate expiration date for cookies. Session cookies expire when the browser is closed, while persistent cookies last until their expiration date.

-- Regularly review and clean up unused or old cookies to avoid unnecessary data retention and potential security risks.

- **Domain and Path Attributes**:

-- Specify the Domain and Path attributes correctly to control which domains and paths in your site can access the cookies, preventing them from being sent to or accessed by unintended parts of your site or application.

- **Data Sensitivity and Storage**:

-- Avoid storing sensitive information (such as passwords, personal identification information, or credit card numbers) directly in cookies due to the risk of interception or unauthorized access.

-- Consider encrypting cookie values to protect the data they contain, especially if they are used for authentication or session management.

- **Performance**: 

-- Be mindful of the size and number of cookies used, as each cookie is sent with every HTTP request to the domain, which can affect performance, especially on mobile networks.

- **Cross-Site Tracking**:

-- Be cautious with third-party cookies, as they can be used for tracking user behavior across different sites. Their use is increasingly being restricted by browser privacy features and regulations.