What are Cookies? — HTTP Cookies Explained
Definition
HTTP cookies are small pieces of data that a server sends to the browser via the Set-Cookie response header. The browser stores the cookie and automatically includes it in subsequent requests to the same domain via the Cookie request header. Cookies are stateful by nature — they allow servers to remember information across requests even though HTTP itself is stateless. They are used for session management, personalization, and tracking.
How It Works
When a server sets a cookie, it sends a header like Set-Cookie: session=abc123; Path=/; HttpOnly; Secure; SameSite=Strict. The browser stores this and automatically attaches Cookie: session=abc123 to subsequent requests matching the domain and path. Cookie attributes control behavior: Expires/Max-Age sets the lifetime (session cookie if omitted), Domain specifies which subdomains receive it, Path limits it to URL paths, HttpOnly prevents JavaScript access (mitigates XSS theft), Secure requires HTTPS, and SameSite controls whether cookies are sent on cross-site requests (preventing CSRF).
Common Use Cases
- ▸Maintaining user sessions after login without re-authentication on each request
- ▸Storing user preferences like language, theme, and layout settings
- ▸Implementing "remember me" functionality with long-lived authentication cookies
- ▸Tracking user behavior across pages for analytics (with consent)
- ▸Passing CSRF tokens for form submission protection
Example
// Server sets a session cookie: Set-Cookie: sid=abc123xyz; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=86400 // Browser automatically sends on subsequent requests: Cookie: sid=abc123xyz // Multiple cookies: Cookie: sid=abc123; theme=dark; lang=en
Related Tools
FAQ
- What is the difference between session cookies and persistent cookies?
- A session cookie has no Expires or Max-Age attribute and is deleted when the browser session ends (the browser is closed). A persistent cookie has an explicit expiration date and survives browser restarts until it expires or is explicitly deleted.
- What does HttpOnly do and why is it important?
- HttpOnly cookies cannot be accessed by JavaScript (document.cookie). This is a critical security attribute for session cookies because it prevents cross-site scripting (XSS) attacks from stealing the session cookie, even if an attacker injects malicious script into the page.
- What is SameSite and how does it prevent CSRF?
- SameSite=Strict prevents the cookie from being sent with any cross-site request, including navigations. SameSite=Lax (the default) allows the cookie on top-level GET navigations but not on cross-site POST, fetch, or iframe requests. This breaks CSRF attacks that rely on a victim's browser automatically including cookies in attacker-triggered requests.