How a cookie keeps you logged in

· 2 min read

#how-it-works#web

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.

A cookie carries a session ID between browser and server The browser sends a login to the server. The server answers with a Set-Cookie header holding a session ID. On every later request the browser sends the ID back in a Cookie header, and the server looks it up in its session store. Browser Server Session store 1 login 2 Set-Cookie 4 look up ID 3 later requests: Cookie: id=…
Simplified: the browser keeps the cookie, and the server keeps the session it points to.

Step by step

  1. You send your username and password to the server.
  2. If they are valid, the server creates a session and replies with Set-Cookie: id=… holding a random ID.
  3. The browser stores the cookie.
  4. On later requests to that site, the browser adds Cookie: id=….
  5. The server finds the ID in its sessions and knows who you are.
  6. 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