The Plain Picture#
A counter clerk with no memory at all. Every time you walk up, they've never seen you before. So the first time, they give you a token with a number on it. After that, you show the token every time, and they look you up in their records.
The Real Names#
HTTP is stateless: each request is independent. The server doesn't automatically remember anything from your previous request. (This is a feature: any server behind a load balancer can handle any request — System design (coming soon).)
A cookie is the token: a small piece of data the server asks the browser to store and send back on every later request to that site.
A session is the server's record of you, found using the ID in the cookie.
Under the Hood#
1. Log in
Browser ── POST /login {email, password} ──────────────────▶ Server
◀── 200 OK
Set-Cookie: session_id=a8f3kq92; HttpOnly; Secure; SameSite=Lax; Max-Age=86400
2. Every later request — the browser attaches it automatically
Browser ── GET /notes/priya
Cookie: session_id=a8f3kq92 ────────────────────▶ Server looks up a8f3kq92 → "Priya"Cookie attributes — each one prevents a specific attack#
| Attribute | Effect | Why |
|---|---|---|
HttpOnly | JavaScript on the page cannot read the cookie | stops stolen cookies via injected scripts (XSS, Security Fundamentals) |
Secure | only sent over HTTPS | never leaks over plain HTTP (Ch 11) |
SameSite=Lax / Strict | not sent on most requests started by other websites | defends against cross-site request forgery (CSRF, 08) |
Max-Age / Expires | when it expires | without it, it's deleted when the browser closes |
Domain / Path | which hosts/paths receive it | scope it as narrowly as possible |
Cookie sessions vs tokens: instead of a cookie with a session ID, many APIs (especially for mobile apps) have the
client store a token and send it in the Authorization header. The trade-offs — including JWTs — are covered in
Authentication and Authorization (coming soon).
Gotchas
Never put secrets or personal data in a cookie's value unless it's encrypted or signed — the user can read and edit their own cookies.
Cookies are sent on every request to that domain, including image requests. Big cookies waste bandwidth.
Check yourself
3 questionsWhat does "HTTP is stateless" mean?
Show answerHide answer
Each request stands alone; the server keeps no automatic memory of earlier requests.
How does a server know it's you on your second request?
Show answerHide answer
It gave your browser a cookie (e.g. a session ID) that the browser sends back on every request; the server looks it up.
What do HttpOnly, Secure and SameSite each protect against?
Show answerHide answer
HttpOnly: scripts stealing the cookie (XSS). Secure: leaking it over unencrypted HTTP. SameSite: other sites
triggering requests that carry it (CSRF).