How a cookie keeps you logged in
A cookie is a small name and value that a server asks your browser to keep and send back. The idea to keep: HTTP does not remember you between requests, so the cookie is how the server recognizes you again.
The short version
Each HTTP request arrives on its own, with no memory of the last one. After you log in, the server creates a session on its side and hands your browser a random session ID inside a cookie. The browser sends that cookie back on later requests, and the server looks the ID up to find you.
Step by step
- You send your username and password to the server.
- If they are valid, the server creates a session and replies with
Set-Cookie: id=…holding a random ID. - The browser stores the cookie.
- On later requests to that site, the browser adds
Cookie: id=…. - The server finds the ID in its sessions and knows who you are.
- If the ID is unknown, you get a generic page or a new login.
| Attribute | What it does |
|---|---|
Secure |
Sent only over HTTPS |
HttpOnly |
Hidden from page scripts |
SameSite |
Decides whether it is sent with cross-site requests |
Why it matters
The cookie carries only a random ID, because the user can see and edit the value. The downside is that anyone who steals the ID can act as you, so Secure and HttpOnly matter. Without Max-Age or Expires it is a session cookie, and the browser deletes it when the browser session ends.
Sources
- RFC 6265, HTTP State Management Mechanism: the Set-Cookie and Cookie headers, the browser sending back only name=value, the attributes
- MDN, Using HTTP cookies: the login and session flow, random session IDs, Secure, HttpOnly, SameSite, session cookies