Understanding Cookies in Web Development

Table of Contents

What are Cookies?

Cookies are small pieces of data that a web server sends to a user's browser. The browser then stores these cookies and sends them back to the same server with subsequent requests. This mechanism allows web applications to "remember" information about the user, such as login status, preferences, or items in a shopping cart, across multiple page views and even over time.

Invented by Lou Montulli in 1994 while working at Netscape, cookies revolutionized how web applications could offer personalized experiences.

How Cookies Work

The process involves the following steps:

  1. A user visits a website.
  2. The web server sends an HTTP response to the browser, which includes a Set-Cookie header. This header contains the cookie's name, value, and other attributes.
  3. The browser receives the cookie and stores it locally, associated with the domain of the website that sent it.
  4. On subsequent requests to the same domain, the browser automatically includes any relevant cookies in the Cookie HTTP header of the request.
  5. The web server can then read these cookies from the incoming request to identify the user or retrieve their preferences.

Setting Cookies (HTTP Headers)

Web servers set cookies using the Set-Cookie header in their HTTP responses.

Server-side Example (Conceptual - e.g., Node.js/Express)

// Setting a persistent cookie
res.cookie('theme', 'dark', {
  expires: new Date(Date.now() + 86400000), // 1 day
  httpOnly: true,
  secure: true,
  sameSite: 'lax'
});

// Setting a session cookie
res.cookie('sessionID', 'abcdef123456', { httpOnly: true });

Reading Cookies (HTTP Headers)

Browsers send cookies back to the server using the Cookie header in HTTP requests.

Incoming Request Header Example

GET /profile HTTP/1.1
Host: example.com
Cookie: theme=dark; sessionID=abcdef123456

Server-side code would then parse this header to extract the cookie values.

Working with Cookies in JavaScript

Client-side JavaScript can access and manipulate cookies through the document.cookie property. However, this access is restricted by the HttpOnly attribute.

JavaScript Example

// Get all cookies
let allCookies = document.cookie;
console.log(allCookies); // e.g., "theme=dark; sessionID=abcdef123456"

// Set a cookie
document.cookie = "username=johnDoe; expires=Thu, 18 Dec 2023 12:00:00 UTC; path=/";

// Read a specific cookie (requires parsing)
function getCookie(name) {
    const nameEQ = name + "=";
    const ca = document.cookie.split(';');
    for(let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) === ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

let username = getCookie("username");
console.log(username); // "johnDoe"

// Delete a cookie (by setting an expiration date in the past)
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
Important: Cookies set with the HttpOnly flag cannot be accessed or modified by client-side JavaScript, which is a crucial security feature.

Common Use Cases for Cookies

Security Considerations

While essential, cookies pose security risks if not handled properly:

Privacy and Regulations

The use of cookies, particularly for tracking and advertising, has raised significant privacy concerns. Regulations like the GDPR (General Data Protection Regulation) and CCPA (California Consumer Privacy Act) mandate that websites obtain user consent before setting non-essential cookies. Developers must be mindful of these regulations and provide clear information to users about cookie usage.

Websites should implement cookie consent banners and offer users control over which types of cookies they accept.