Adding memory to HTTP
HTTP is stateless, so each request stands alone. A cookie is a small piece of data the server sends with Set Cookie, which the browser stores and returns on later requests to the same site. This lets the server recognize a returning visitor.
Sessions on top of cookies
A common pattern stores a random session identifier in a cookie while keeping the real user data on the server. The cookie is just a key; the server looks up the matching session record. This keeps sensitive data off the client and lets the server revoke a session instantly.
Important attributes
- HttpOnly hides the cookie from scripts, blunting cross site scripting theft.
- Secure sends it only over encrypted connections.
- SameSite limits whether the cookie rides along on cross site requests, reducing forgery.
- Max Age or Expires controls how long the browser keeps it.
Forgetting Secure or HttpOnly is a frequent source of account hijacking, so defaults should be strict.
Key idea
Cookies give stateless HTTP memory, and a session id cookie lets the server hold real data while attributes like HttpOnly and SameSite protect it.