Cookie Fundamentals

What Are Cookies?

Cookies are small pieces of data stored in a user's web browser. They were originally designed to maintain state in stateless HTTP protocol, allowing websites to remember information about users between page visits.

Basic Concepts

Purpose

How Cookies Work

  1. Server Sets Cookie: When a browser requests a page, the server can send a Set-Cookie header
  2. Browser Stores Cookie: The browser stores the cookie according to its attributes
  3. Browser Sends Cookie: On subsequent requests to the same domain, the browser sends the cookie in a Cookie header
  4. Server Receives Cookie: The server can read and use the cookie value

A cookie consists of:

Example

Set-Cookie: session_id=abc123xyz; Domain=example.com; Path=/; Secure; HttpOnly

This sets a cookie named session_id with value abc123xyz that:

  1. Creation: Server sends Set-Cookie header
  2. Storage: Browser stores cookie based on attributes
  3. Transmission: Browser sends cookie in Cookie header on matching requests
  4. Expiration: Cookie expires based on Expires or Max-Age attribute
  5. Deletion: Browser removes expired cookies or cookies with past expiration date
sequenceDiagram participant Browser participant Server participant CookieStorage Browser->>Server: GET /page HTTP/1.1 Server->>Browser: HTTP/1.1 200 OK
Set-Cookie: session=abc123
Domain=example.com
Path=/
Secure
HttpOnly
SameSite=Strict
Max-Age=3600 Browser->>CookieStorage: Store cookie (based on attributes) CookieStorage-->>Browser: Cookie stored Note over Browser,CookieStorage: Cookie stored with Domain=example.com, Path=/, Max-Age=3600 Browser->>Server: GET /dashboard HTTP/1.1
Cookie: session=abc123 Server->>Browser: HTTP/1.1 200 OK
Content: Dashboard HTML Note over Browser: After 1 hour (Max-Age expired) CookieStorage->>CookieStorage: Remove expired cookie

Key Terminology

Next Steps