Sub topic 12
Cookies and sessions
This chapter assumes you can read HTTP requests and responses, know what headers are, and understand that a server handles each request on its own. You should also know how a server reads a request and writes a response.
Why HTTP needs help remembering
HTTP is stateless. Each request stands alone, and the server does not automatically know that two requests came from the same person. A login would be useless if you had to send your password with every click.
Cookies fix this. A cookie is a small piece of data that the server asks the browser to store and send back on later requests. A session is the server-side record that the cookie points to, such as "this browser is logged in as user 42".
The cookie exchange
The server sets a cookie with the Set-Cookie response header. The browser stores it and attaches it to later requests to the same site in the Cookie header.
HTTP/1.1 200 OK
Set-Cookie: session_id=abc123; HttpOnly; Secure; SameSite=Lax; Path=/
GET /account HTTP/1.1
Host: example.com
Cookie: session_id=abc123
Sessions on the server
The cookie value should be an unguessable random identifier, not the user's data. The server keeps a table that maps each identifier to session data. A minimal sketch in Node.js shows the idea:
import { createServer } from "node:http";
import { randomUUID } from "node:crypto";
const sessions = new Map();
const server = createServer((req, res) => {
const cookie = req.headers.cookie ?? "";
const match = /(?:^|;\s*)session_id=([^;]+)/.exec(cookie);
let id = match?.[1];
if (!id || !sessions.has(id)) {
id = randomUUID();
sessions.set(id, { visits: 0 });
res.setHeader(
"Set-Cookie",
`session_id=${id}; HttpOnly; SameSite=Lax; Path=/`
);
}
const session = sessions.get(id);
session.visits += 1;
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
res.end(`Visit number ${session.visits}\n`);
});
server.listen(3000);Open http://localhost:3000 and reload. The counter rises because the browser returns the same identifier each time. The Secure attribute is left out here because the local server uses plain HTTP. Use it in production.
Cookie attributes
| Attribute | Effect |
|---|---|
| `HttpOnly` | JavaScript cannot read the cookie, which limits theft through cross-site scripting. |
| `Secure` | The browser sends the cookie only over HTTPS. |
| `SameSite` | Controls whether the cookie is sent on cross-site requests. `Lax` and `Strict` reduce cross-site request forgery risk. |
| `Path` | Limits the cookie to URLs under this path. |
| `Max-Age` / `Expires` | Sets a lifetime. Without one, the cookie is a session cookie and is dropped when the browser closes. |
| `Domain` | Shares the cookie with subdomains. Omit it to restrict the cookie to the exact host. |
Common errors
- Cookie never sent back. Check
Path,Domain, andSecure. ASecurecookie set over HTTP is rejected or never returned. - Session lost on every request. The server may keep sessions in memory behind several instances. Each instance has its own table. Use a shared store such as a database.
- Storing data in the cookie. Anyone can edit a cookie. Keep sensitive data on the server.
- Cookie too large. Browsers limit a cookie to about 4 KB, and every request carries it.
Exercise
A site sets Set-Cookie: session_id=abc123; HttpOnly; Secure. A script on the page runs document.cookie. Does it see session_id, and does the browser send the cookie on a request to http://example.com/?
Show answer
The script does not see it, because HttpOnly hides the cookie from JavaScript. The browser does not send it on a plain HTTP request, because Secure limits it to HTTPS.