Upgrade & Secure Your Future with DevOps, SRE, DevSecOps, MLOps!

We spend hours scrolling social media and waste money on things we forget, but won’t spend 30 minutes a day earning certifications that can change our lives.
Master in DevOps, SRE, DevSecOps & MLOps by DevOpsSchool!

Learn from Guru Rajesh Kumar and double your salary in just one year.


Get Started Now!

Understanding Cookies: Concepts, Use Cases, Architecture and Getting Started

What Are Cookies?

Cookies are small text files that web servers send to a user’s web browser, which stores them on the client’s device. These files contain data that help websites remember information about users, such as login status, preferences, or tracking identifiers.

Cookies were introduced in the early 1990s to address the challenge posed by the HTTP protocol’s statelessness — meaning that each request to a server is independent and does not inherently carry information about previous interactions. Cookies allow websites to “remember” users and their interactions across sessions.

Each cookie consists of key-value pairs and a set of metadata that define the cookie’s scope, lifespan, and security properties. The browser automatically includes relevant cookies in subsequent HTTP requests to the appropriate domains, enabling servers to maintain a continuous user experience.


Major Use Cases of Cookies

Cookies are vital across many web application domains due to their ability to persist state and track information. Below are key use cases:

1. Session Management

Cookies enable websites to identify returning users and maintain session continuity without requiring users to authenticate on every page load. For example, after logging in, a session cookie keeps a user logged in until they log out or the session expires.

2. User Preferences and Personalization

Cookies store user settings such as language preferences, theme choices, or layout configurations. When a user revisits, the site can retrieve these preferences and tailor the interface accordingly.

3. Shopping Cart Persistence

E-commerce websites leverage cookies to remember products added to a user’s cart even if the browser is closed and reopened before checkout, enhancing the shopping experience.

4. Tracking and Analytics

Cookies collect data on user behavior, page visits, and navigation paths. Analytics platforms use cookies to generate insights about website performance and user engagement. Advertising networks use third-party cookies to track users across sites for targeted ads.

5. Security

Cookies help secure web applications by storing tokens or flags used in authentication workflows, CSRF protection, and managing user permissions.

6. Legal Compliance

Cookies assist in storing consent information, ensuring compliance with data protection regulations like the General Data Protection Regulation (GDPR) and California Consumer Privacy Act (CCPA).


How Cookies Work Along with Architecture

Cookies operate at the intersection of HTTP protocol, client (browser) storage, and server-side application logic. The architecture supporting cookie functionality includes several components:

1. HTTP Headers and Communication

  • When a client sends a request to a server, it includes a Cookie header containing cookies relevant to the request URL’s domain and path.
  • The server can send back one or more Set-Cookie headers in its response to instruct the browser to store new cookies or update existing ones.

Example HTTP response header:

Set-Cookie: sessionId=abc123; Expires=Wed, 09 Jun 2025 10:18:14 GMT; Path=/; Secure; HttpOnly; SameSite=Strict

2. Browser Cookie Storage

  • Browsers maintain a “cookie jar” storing cookies by domain and path.
  • They enforce scoping rules, ensuring cookies are only sent to appropriate URLs.
  • Cookies are stored on disk or in memory depending on persistence.

3. Cookie Attributes and Their Impact

  • Domain: Restricts the domains to which the cookie will be sent. Cookies set for example.com are sent to sub.example.com but not to otherdomain.com.
  • Path: Restricts the URL paths on the domain for which the cookie is valid.
  • Expires/Max-Age: Defines when a cookie will be deleted. Session cookies expire when the browser closes; persistent cookies survive beyond sessions.
  • Secure: Ensures cookies are only sent over HTTPS connections.
  • HttpOnly: Prevents client-side JavaScript from accessing cookies, mitigating some XSS attacks.
  • SameSite: Controls cross-site cookie sharing to prevent CSRF and privacy leaks. Values include Strict, Lax, or None.

4. Server-Side Handling

  • Servers read cookies from incoming requests and use their data to maintain sessions, authenticate users, or track state.
  • Servers can update or delete cookies by sending updated Set-Cookie headers.

5. Third-Party Cookies

  • These are cookies set by domains other than the one shown in the browser’s address bar, typically used by advertisers or analytics services.
  • Modern browsers are increasingly restricting third-party cookies due to privacy concerns.

Detailed Workflow of Cookies

1. Initial Visit

  • User visits a website; the browser sends a request without cookies.

2. Server Response with Cookies

  • Server responds with Set-Cookie headers to establish sessions or preferences.

3. Browser Stores Cookies

  • The browser saves cookies respecting domain, path, security attributes.

4. Subsequent Requests

  • Browser automatically includes relevant cookies in HTTP requests for that domain/path.

5. Server Processes Cookies

  • Server uses cookies to authenticate the user, retrieve session data, or customize the response.

6. Cookie Updates

  • Server can update cookies by sending new Set-Cookie headers with modified values or expiration.

7. Cookie Expiration or Deletion

  • Cookies expire naturally after their expiry time or are deleted by explicit instructions or user actions.

Step-by-Step Getting Started Guide for Cookies

Step 1: Understand Cookie Fundamentals

Familiarize yourself with cookie components — name, value, domain, path, expiry, and security flags.

Step 2: Setting Cookies from the Server

Example: Node.js Express

res.cookie('userId', '12345', {
  maxAge: 24 * 60 * 60 * 1000, // 1 day
  httpOnly: true,
  secure: true,
  sameSite: 'Strict',
  path: '/'
});

Step 3: Reading Cookies on Server

Using the cookie-parser middleware:

const userId = req.cookies.userId;
console.log(`User ID from cookie: ${userId}`);

Step 4: Creating Cookies with JavaScript

document.cookie = "theme=dark; max-age=3600; path=/";

Step 5: Deleting Cookies

Set expiration date in the past:

document.cookie = "theme=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

Step 6: Implement Security Best Practices

  • Always set HttpOnly and Secure flags where possible.
  • Use SameSite attributes to reduce CSRF vulnerabilities.
  • Avoid storing sensitive information directly in cookies.

Step 7: Respect Privacy Regulations

  • Implement consent banners.
  • Provide users with options to manage cookie preferences.
  • Document cookie usage in privacy policies.

Advanced Topics and Considerations

1. Cookie Size and Limits

  • Most browsers limit individual cookie size to 4KB.
  • There is a per-domain cookie limit (around 20–50 cookies).
  • Exceeding limits causes older cookies to be evicted.

2. Third-Party Cookie Restrictions

  • Browsers increasingly block or restrict third-party cookies.
  • Alternatives include localStorage, IndexedDB, or server-side sessions.

3. Alternatives to Cookies

  • Web Storage API (localStorage, sessionStorage) for client-side storage.
  • JWT tokens for stateless authentication.

4. Cross-Origin Resource Sharing (CORS) and Cookies

  • Cookies require careful configuration of CORS headers and credentials policies to work across domains.
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x