AlgoPlusAlgoPlus
Learn/Web
Lesson

Cookies, Sessions & Login

HTTP forgets you between requests. A cookie carrying a session id — set at login, resent automatically — is how a site recognises you.

9 min read Watch it move Build it

HTTP is stateless: each request is independent and the server remembers nothing about your earlier ones. So how does a site keep you logged in? At login it hands the browser a cookie holding a session id; the browser then resends that cookie on *every* later request, and the server uses it to recognise you.

Cookies — Set-Cookie and its flags

A cookie is a small named value the browser stores for a site and sends back automatically. The server sets one with the Set-Cookie response header, and the browser echoes it on future requests via the Cookie header. The security flags matter as much as the value:

  1. 1HttpOnly — hide the cookie from JavaScript, so a script-injection (XSS) attack can't steal the session id.
  2. 2Secure — send it only over HTTPS, never plain HTTP.
  3. 3SameSite=Lax / Strict / None — control whether the cookie rides along on *cross-site* requests; Lax (the default) blocks it on most cross-site POSTs, blunting CSRF.
  4. 4Max-Age / Expires — how long the cookie lives before the browser drops it.

The login flow

# 1. Browser submits credentials
POST /login HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded

user=alice&pass=hunter2

# 2. Server verifies, creates a session, hands back a cookie
HTTP/1.1 200 OK
Set-Cookie: session=9f8a...e21; HttpOnly; Secure; SameSite=Lax; Max-Age=86400

# 3. Every later request carries it automatically
GET /account HTTP/1.1
Host: example.com
Cookie: session=9f8a...e21

Server sessions vs stateless tokens (JWT)

There are two ways to make that id mean something. With server-side sessions, the cookie holds only an *opaque* random id; the real data ('this is alice, an admin') lives in a session store on the server, looked up on each request. With a stateless token (JWT), the cookie carries the identity *itself* inside a signed token, so the server can trust it without any lookup.

OperationTimeSpace
Server session — recognise a request · id is opaque; data lives server-side; easy to revoke1 store lookupgrows with users
JWT / token — recognise a request · identity travels in the token; harder to revoke earlyverify signatureno server store
Session fixation and CSRF
Session fixation: if the server keeps the *same* session id from before login, an attacker who planted that id is now logged in as you — so always rotate the id at login. CSRF: because the browser attaches the cookie automatically, another site can trigger a request *as you* — SameSite cookies plus anti-CSRF tokens are the defence.
Check yourself
With classic server-side sessions, what does the browser's cookie actually contain?