Cookies: What They Are and How They Work

Cookies are small pieces of data stored in the user’s browser by websites. They are used to maintain sessions, store preferences, and track user activity. Cookies play a key role in authentication and user experience on the web.

Cookies: What They Are and How They Work

Cookies are small pieces of data stored in the user's browser by websites. They are one of the most fundamental technologies of the web, enabling websites to remember information between page loads and across browsing sessions. Without cookies, the web would be stateless, with every request being completely independent and websites unable to remember who you are, what is in your shopping cart, or your language preferences.

Cookies play a crucial role in authentication, session management, personalization, and tracking. Understanding how cookies work is essential for web developers, security professionals, and anyone building modern web applications. To understand cookies properly, it is helpful to be familiar with concepts like HTTP protocol, session management, web security fundamentals, and authentication mechanisms.

What Are Cookies

An HTTP cookie (also called web cookie, browser cookie) is a small piece of data sent from a website and stored in the user's web browser while the user is browsing. Cookies are designed to be a reliable mechanism for websites to remember stateful information or to record the user's browsing activity.

  • Name-Value Pair: Each cookie consists of a name and a value (e.g., sessionId=abc123).
  • Domain: The domain that created the cookie and can read it.
  • Path: The URL path that must exist in the requested URL for the cookie to be sent.
  • Expiration: When the cookie expires (session cookie vs persistent cookie).
  • Secure Flag: Cookie is only sent over HTTPS.
  • HttpOnly Flag: Cookie cannot be accessed by JavaScript (prevents XSS theft).
  • SameSite Flag: Controls when cookie is sent with cross-site requests (CSRF protection).
Cookie structure example:
Set-Cookie: sessionId=abc123def456; Domain=example.com; Path=/; Expires=Wed, 21 Oct 2025 07:28:00 GMT; Secure; HttpOnly; SameSite=Lax

┌─────────────────────────────────────────────────────────────┐
│  Name: sessionId                                            │
│  Value: abc123def456                                        │
│  Domain: example.com                                        │
│  Path: /                                                    │
│  Expires: Wed, 21 Oct 2025 07:28:00 GMT                    │
│  Max-Age: 3600                                              │
│  Secure: true                                               │
│  HttpOnly: true                                             │
│  SameSite: Lax                                              │
└─────────────────────────────────────────────────────────────┘

Why Cookies Matter

Cookies are essential for modern web functionality. They enable websites to provide personalized, stateful experiences across multiple requests and sessions.

  • Session Management: Keep users logged in across page visits. Store session identifiers to maintain state.
  • Personalization: Remember user preferences like language, theme, or layout settings.
  • Tracking and Analytics: Collect anonymous usage data to understand how visitors interact with your site.
  • Shopping Carts: Store cart contents without requiring user login.
  • Advertising: Deliver relevant ads and measure campaign effectiveness.
  • Security: CSRF tokens, session validation, and fingerprinting.

How Cookies Work

Cookies are created by the server and sent to the browser via the Set-Cookie HTTP response header. The browser stores the cookie and automatically includes it in subsequent requests to the same domain using the Cookie header.

Cookie lifecycle flow:
┌─────────────────────────────────────────────────────────────┐
│                    Cookie Lifecycle                          │
├─────────────────────────────────────────────────────────────┤
│                                                              │
│  1. Server sends Set-Cookie header in HTTP response         │
│                                                              │
│  2. Browser stores cookie (name, value, attributes)         │
│                                                              │
│  3. Browser includes cookie in Cookie header of subsequent  │
│     requests to the same domain                             │
│                                                              │
│  4. Server reads cookie value and processes request         │
│                                                              │
│  5. Cookie expires (session end or expiration date)         │
│                                                              │
│  6. Browser deletes expired cookie                          │
│                                                              │
└─────────────────────────────────────────────────────────────┘
HTTP request-response cookie example:
// Server Response (sets cookie)
HTTP/1.1 200 OK
Content-Type: text/html
Set-Cookie: sessionId=abc123; Path=/; HttpOnly; Secure; SameSite=Lax
Set-Cookie: theme=dark; Max-Age=31536000; Path=/
Set-Cookie: preferredLanguage=en; Domain=example.com; Path=/

// Browser stores cookies

// Subsequent Request (browser sends cookies)
GET /dashboard HTTP/1.1
Host: example.com
Cookie: sessionId=abc123; theme=dark; preferredLanguage=en

// Server reads cookies to identify user and preferences

Types of Cookies

Cookies can be classified by their duration, origin, and purpose. Understanding the different types helps you choose the right cookie for your use case.

Cookie Type Description Duration
Session Cookie Stored only in memory, deleted when browser closes Until browser closes
Persistent Cookie Stored on disk, persists across browser restarts Based on Max-Age or Expires attribute
First-Party Cookie Set by the domain the user is visiting Varies
Third-Party Cookie Set by a domain different from the one in the address bar Varies (being phased out by browsers)
Secure Cookie Only sent over HTTPS connections Varies
HttpOnly Cookie Cannot be accessed by JavaScript (XSS protection) Varies
SameSite Cookie Controls cross-site request behavior (CSRF protection) Varies

Cookie Attributes

Cookie attributes control how cookies behave, when they are sent, and what security restrictions apply. Setting the right attributes is crucial for security and functionality.

Expiration Attributes

Max-Age and Expires:
# Session cookie (no expiration)
Set-Cookie: sessionId=abc123

# Persistent cookie with Max-Age (seconds)
Set-Cookie: rememberMe=xyz789; Max-Age=2592000  # 30 days

# Persistent cookie with Expires (HTTP-date)
Set-Cookie: preference=dark; Expires=Wed, 21 Oct 2025 07:28:00 GMT

# Max-Age takes precedence over Expires in modern browsers

Domain and Path

Domain and Path examples:
# Cookie only sent to exact domain
Set-Cookie: user=john; Domain=example.com

# Cookie sent to all subdomains (leading dot indicates all subdomains)
Set-Cookie: session=abc123; Domain=.example.com

# Cookie only sent to /admin path
Set-Cookie: adminToken=xyz; Path=/admin

# Cookie sent to all paths (default)
Set-Cookie: theme=dark; Path=/

Security Attributes

Secure and HttpOnly:
# Secure flag - only sent over HTTPS
Set-Cookie: sessionId=abc123; Secure

# HttpOnly flag - not accessible via JavaScript
Set-Cookie: sessionId=abc123; HttpOnly

# Both flags together (recommended for session cookies)
Set-Cookie: sessionId=abc123; Secure; HttpOnly

# Without HttpOnly, JavaScript can read the cookie
// document.cookie returns all non-HttpOnly cookies
// This makes cookies vulnerable to XSS attacks

SameSite Attribute

SameSite is a critical security attribute that protects against CSRF attacks. It controls whether cookies are sent with cross-site requests.

SameSite values:
# Strict - cookie only sent for same-site requests (most secure)
Set-Cookie: sessionId=abc123; SameSite=Strict

# Lax - cookie sent for same-site and top-level navigation (recommended)
Set-Cookie: sessionId=abc123; SameSite=Lax

# None - cookie sent for all requests (requires Secure flag)
Set-Cookie: sessionId=abc123; SameSite=None; Secure

# Example: Lax allows navigation from external links but blocks form POST
# Example: Strict blocks all cross-site usage including navigation

Session Management with Cookies

Cookies are the most common mechanism for managing user sessions. A session cookie stores a unique identifier that the server uses to look up session data.

Session cookie implementation (PHP example):
<?php
// Start session (sets session cookie automatically)
session_start();

// Set session data
$_SESSION['user_id'] = 123;
$_SESSION['username'] = 'john_doe';
$_SESSION['role'] = 'admin';

// Configure secure session cookie
session_set_cookie_params([
    'lifetime' => 3600,
    'path' => '/',
    'domain' => 'example.com',
    'secure' => true,
    'httponly' => true,
    'samesite' => 'Lax'
]);

// Login successful - regenerate session ID to prevent fixation
session_regenerate_id(true);

// Logout - destroy session
session_destroy();
setcookie(session_name(), '', time() - 3600, '/');
Session cookie verification (Node.js/Express example):
const session = require('express-session');

app.use(session({
    name: 'sessionId',
    secret: 'your-secret-key',
    resave: false,
    saveUninitialized: false,
    cookie: {
        secure: true,        // HTTPS only
        httpOnly: true,      // No JavaScript access
        maxAge: 3600000,     // 1 hour
        sameSite: 'lax'      // CSRF protection
    }
}));

// Check authentication middleware
function requireAuth(req, res, next) {
    if (req.session.userId) {
        next();
    } else {
        res.status(401).json({ error: 'Unauthorized' });
    }
}

Setting and Reading Cookies

Cookies can be set from the server using the Set-Cookie header or from JavaScript using document.cookie. Reading cookies is done automatically by the browser or via JavaScript.

Setting cookies from JavaScript:
// Set a cookie (expires when browser closes)
document.cookie = "theme=dark";

// Set a cookie with expiration (30 days)
const expiryDate = new Date();
expiryDate.setDate(expiryDate.getDate() + 30);
document.cookie = `preference=dark; expires=${expiryDate.toUTCString()}; path=/`;

// Set cookie with attributes
document.cookie = "sessionId=abc123; Secure; SameSite=Strict; path=/";

// Note: HttpOnly cookies cannot be set or read by JavaScript
// Note: Secure cookies require HTTPS
Reading cookies in JavaScript:
// Read all cookies (returns semicolon-separated string)
const allCookies = document.cookie;
// Output: "theme=dark; sessionId=abc123; preference=dark"

// Parse cookies into object
function getCookie(name) {
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    if (parts.length === 2) return parts.pop().split(';').shift();
    return null;
}

const theme = getCookie('theme');
console.log(theme); // "dark"

// Delete a cookie (set expiration to past date)
document.cookie = "theme=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";

Cookie Security Best Practices

Cookies can be exploited if not properly secured. Following these best practices protects your users and your application.

  • Use HttpOnly Flag: Prevents JavaScript access, mitigating XSS attacks that try to steal session cookies.
  • Use Secure Flag: Ensures cookies are only sent over HTTPS, preventing interception over HTTP.
  • Use SameSite Flag: Use SameSite=Lax or Strict to prevent CSRF attacks.
  • Set Appropriate Expiration: Use short-lived session cookies for authentication, longer for preferences.
  • Regenerate Session IDs: Create new session IDs after login to prevent session fixation.
  • Store Minimal Data: Store only identifiers in cookies, keep sensitive data on the server.
  • Use Signed Cookies: Sign cookies to detect tampering (not encrypted, but integrity verified).
  • Limit Cookie Size: Keep cookies small (under 4KB) for performance and compatibility.
  • Set Appropriate Path: Restrict cookie scope to necessary paths.

Third-Party Cookies and Privacy

Third-party cookies are set by domains other than the one the user is visiting. They are commonly used for cross-site tracking, advertising, and analytics. Due to privacy concerns, browsers are increasingly blocking third-party cookies.

Third-party cookie restrictions by browser:
# Safari (Intelligent Tracking Prevention - ITP)
- Blocks third-party cookies by default
- Limits first-party cookie lifespan for tracked domains

# Firefox (Enhanced Tracking Protection)
- Blocks third-party cookies by default
- Blocks known trackers

# Chrome (Privacy Sandbox)
- Phasing out third-party cookies by 2025
- Requires SameSite=None and Secure for cross-site usage

# Brave
- Blocks third-party cookies by default
- Additional fingerprinting protection

# Alternative solutions for cross-site needs:
- First-party cookies with partitioned storage (CHIPS)
- Storage Access API
- Federated Credential Management (FedCM)

Cookie Size and Limitations

Cookies have practical limitations that affect how much data you can store and how many cookies you can set.

  • Maximum Cookie Size: Most browsers limit each cookie to 4KB (4096 bytes).
  • Maximum Cookies per Domain: 20-50 cookies per domain (varies by browser).
  • Total Cookie Limit: Approximately 50KB per domain total.
  • Performance Impact: Large cookies are sent with every request, increasing bandwidth usage.
  • Alternative Storage: Use localStorage or sessionStorage for larger client-side data (5-10MB).
When to use localStorage instead of cookies:
// Cookies (sent with every request)
// Good for: Session IDs, authentication tokens, CSRF tokens
document.cookie = "sessionId=abc123; Secure; HttpOnly";

// localStorage (not sent with requests)
// Good for: User preferences, UI state, cached data
localStorage.setItem('theme', 'dark');
localStorage.setItem('language', 'en');
localStorage.setItem('sidebar-collapsed', 'true');

// sessionStorage (cleared when tab closes)
sessionStorage.setItem('form-data', JSON.stringify(formData));

// IndexedDB (large structured data)
// Good for: Offline data, large datasets, files

Common Cookie Mistakes to Avoid

Even experienced developers make mistakes when implementing cookies. Being aware of these common pitfalls helps you avoid them.

  • Storing Sensitive Data in Cookies: Never store passwords, credit cards, or personal data directly in cookies.
  • Missing Secure Flag on HTTPS: Without Secure flag, cookies can be intercepted over HTTP.
  • Missing HttpOnly for Session Cookies: Allows XSS attacks to steal session tokens.
  • Not Validating Cookie Data: Always validate and sanitize cookie data like any user input.
  • Using Cookies for Non-Identifier Data: Use localStorage for large, client-only data to reduce request size.
  • Not Handling Cookie Expiration: Session cookies should expire appropriately; persistent cookies should have reasonable lifespans.
  • Setting Too Broad Path: Cookies accessible to unnecessary paths increase exposure.
  • Not Using SameSite: Missing SameSite attribute leaves CSRF vulnerabilities.

Testing Cookies

Browser developer tools provide powerful features for inspecting and debugging cookies.

Chrome DevTools cookie inspection:
1. Open DevTools (F12 or Ctrl+Shift+I)
2. Go to Application tab
3. Select Cookies under Storage section
4. View all cookies with their attributes:
   - Name
   - Value
   - Domain
   - Path
   - Expires / Max-Age
   - Size
   - HttpOnly
   - Secure
   - SameSite

# Also visible in Network tab:
1. Select a request
2. Look for Cookie header in Request Headers
3. Look for Set-Cookie header in Response Headers

# Clear cookies:
1. Application tab > Storage > Clear site data
2. Or use: document.cookie = "name=; expires=Thu, 01 Jan 1970 00:00:00 UTC"

Frequently Asked Questions

  1. What is the difference between session and persistent cookies?
    Session cookies are stored in memory and deleted when the browser closes. Persistent cookies have an expiration date and are stored on disk, surviving browser restarts.
  2. Can cookies be stolen?
    Yes. Cookies can be stolen via XSS attacks (if not HttpOnly), network sniffing (if not Secure), or malware on the user's device. Proper cookie attributes mitigate these risks.
  3. What is cookie expiration?
    Cookie expiration determines how long the browser keeps the cookie. Session cookies expire when the browser closes. Persistent cookies expire at a specified date or after a Max-Age duration.
  4. What is the difference between localStorage and cookies?
    Cookies are sent with every HTTP request. localStorage data is never sent to the server. localStorage offers much larger storage (5-10MB vs 4KB). Use cookies for authentication and server-required data; use localStorage for client-only preferences.
  5. What is a supercookie?
    A supercookie is a cookie with an unusually broad domain (e.g., .com) that can be accessed by many sites. Modern browsers restrict supercookies to prevent tracking.
  6. What should I learn next after understanding cookies?
    After mastering cookies, explore session management for user state, CSRF protection for security, security headers for cookie protection, and authentication for user verification.

Conclusion

Cookies are a fundamental technology of the web, enabling stateful interactions in an otherwise stateless HTTP protocol. They power session management, authentication, personalization, and countless other features that users expect from modern websites. Understanding how cookies work, their attributes, and security implications is essential for every web developer.

Proper cookie implementation requires attention to security attributes: HttpOnly prevents XSS theft, Secure ensures HTTPS-only transmission, and SameSite protects against CSRF attacks. Session cookies should be short-lived, regenerate after login, and store only identifiers rather than sensitive data. For client-only data, consider using localStorage or sessionStorage instead of cookies to reduce request overhead.

As browsers evolve and privacy concerns grow, cookie behavior continues to change. Third-party cookies are being phased out, and new standards like CHIPS and Storage Access API are emerging. Staying informed about these changes ensures your applications remain functional and secure.

To deepen your understanding, explore related topics like session management for maintaining user state, CSRF protection for securing cookies, security headers for additional protection, and authentication mechanisms for user verification. Together, these skills form a complete foundation for building secure, user-friendly web applications.