HTTP forgets you between requests. A cookie carrying a session id — set at login, resent automatically — is how a site recognises you.
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.
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:
HttpOnly — hide the cookie from JavaScript, so a script-injection (XSS) attack can't steal the session id.Secure — send it only over HTTPS, never plain HTTP.SameSite=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.Max-Age / Expires — how long the cookie lives before the browser drops it.# 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...e21There 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.
SameSite cookies plus anti-CSRF tokens are the defence.