HTTP Cookies and State Management
You'll learn how cookies enable stateful sessions in the stateless HTTP protocol.
The Problem: HTTP is Stateless
Remember that HTTP follows a simple request-response model where each transaction is independent. The server doesn't naturally "remember" who you are between requests. Visit a shopping site, add an item to your cart, click to another page—and without something extra, the server would forget your cart entirely.
How Cookies Solve This
Cookies are small pieces of data that the server sends to your browser in an HTTP response header. Your browser stores them and automatically includes them in subsequent requests to the same server.
Think of it like a coat-check ticket at a restaurant. The server hands you a numbered ticket (cookie) when you first arrive. Every time you come back to your table, you show that ticket, and the staff knows exactly which coat (session data) belongs to you—even though they serve hundreds of customers.
The Cookie Flow
-
Server sets cookie: In an HTTP response header, the server includes:
Set-Cookie: session_id=abc123; Path=/; HttpOnly -
Browser stores it: Your browser saves
session_id=abc123associated with that domain. -
Browser sends it back: On every subsequent request to that domain, the browser automatically includes:
Cookie: session_id=abc123 -
Server recognizes you: The server reads the cookie value and retrieves your session data (cart contents, login status, preferences, etc.) from its storage.
Cookies can have attributes like expiration dates, path restrictions, and security flags (HttpOnly, Secure).
Key Takeaway: Cookies transform stateless HTTP into a stateful experience by letting servers tag clients with identifiers that persist across multiple request-response cycles, enabling features like login sessions and shopping carts.