Sub topic 12
Cookies and sessions
This chapter assumes you can read an HTTP request and response, know what headers are, and have seen how a server handles a request. It builds on the header and server-handling chapters.
The problem: HTTP forgets
HTTP is stateless. Each request stands alone, and the server does not remember the previous one. If you log in with one request and then ask for /account with the next, the server has no built-in way to know that both came from the same person.
Cookies solve this. A cookie is a small piece of text that the server asks the browser to store, and that the browser then sends back automatically on later requests to the same site. A session is the server-side idea built on top: a record of who a visitor is and what they have done, found by looking up an identifier carried in a cookie.
How a cookie travels
The exchange uses two headers. The server sets a cookie with Set-Cookie in a response. The browser returns it with Cookie in later requests.
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
The first part is a response. The second is a request the browser sends later. The cookie has a name (session_id), a value (abc123), and attributes after the semicolons. The attributes control how the browser handles the cookie. They are not sent back. Only name=value pairs appear in the Cookie header.
Sessions: where the data lives
There are two common designs.
- Server-side sessions. The cookie holds only a random identifier. The server keeps the real data (user ID, cart, permissions) in memory, a database, or a store such as Redis. The server can end a session at any time by deleting its record.
- Client-side sessions. The cookie holds the data itself, usually signed so the browser cannot alter it, and sometimes encrypted. No server lookup is needed. The trade-off is that you cannot easily revoke one session before it expires, and the cookie grows with the data.
Most frameworks default to the first design. The session identifier must be unguessable, so it should come from a cryptographically secure random generator and have enough length (at least 128 bits is a common guideline). A guessable identifier lets an attacker impersonate users.
Cookie attributes
Attributes decide where a cookie is sent and who can read it.
| Attribute | Effect |
|---|---|
| `Expires=<date>` or `Max-Age=<seconds>` | Makes the cookie persistent until that time. Without either, it is a session cookie that the browser discards when it closes (browsers may restore it, so do not rely on this). |
| `Path=/` | Sends the cookie only for URLs under this path. |
| `Domain=example.com` | Also sends it to subdomains. Without `Domain`, the cookie goes only to the exact host that set it. |
| `Secure` | Sends the cookie only over HTTPS. |
| `HttpOnly` | Hides the cookie from JavaScript (`document.cookie`). |
| `SameSite=Strict`, `Lax`, or `None` | Controls whether the cookie is sent on cross-site requests. `None` requires `Secure`. |
Notice the Domain rule. Setting Domain widens exposure, because every subdomain then receives the cookie. Omit it unless you need sharing.
Building a session in Node.js
The following server uses only built-in modules. It keeps sessions in a Map, creates one on first visit, and counts visits. It is a teaching sketch. A real application would use a framework's session library and a shared store.
import { createServer } from "node:http";
import { randomBytes } from "node:crypto";
const sessions = new Map();
function parseCookies(header = "") {
const cookies = {};
for (const part of header.split(";")) {
const index = part.indexOf("=");
if (index === -1) continue;
const name = part.slice(0, index).trim();
cookies[name] = part.slice(index + 1).trim();
}
return cookies;
}
const server = createServer((req, res) => {
const cookies = parseCookies(req.headers.cookie);
let id = cookies.session_id;
let session = sessions.get(id);
if (!session) {
id = randomBytes(32).toString("hex");
session = { visits: 0 };
sessions.set(id, session);
res.setHeader(
"Set-Cookie",
`session_id=${id}; HttpOnly; SameSite=Lax; Path=/; Max-Age=3600`
);
}
session.visits += 1;
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
res.end(`Visit number ${session.visits}\n`);
});
server.listen(3000);The server reads req.headers.cookie, looks up the identifier, and creates a new session if none matches. It generates 32 random bytes, which is 256 bits. Secure is left out only because the example runs on plain http://localhost. Add it in production.
You can watch the cookie with curl. The -c option saves cookies to a file and -b sends them back.
curl -v -c jar.txt -b jar.txt http://localhost:3000/
curl -v -c jar.txt -b jar.txt http://localhost:3000/The first response shows Set-Cookie. The second request shows Cookie, and the body reads Visit number 2. Without the cookie jar, every request would return Visit number 1.
Security concerns
Theft through scripts
If an attacker injects JavaScript into your page (cross-site scripting, or XSS), the script can read document.cookie and send it away. HttpOnly blocks that read. It does not stop the script from making requests that carry the cookie, so it limits damage and does not remove the XSS flaw.
Theft on the network
Without HTTPS, anyone on the path can read the Cookie header. Secure keeps the cookie off plain HTTP connections.
Cross-site request forgery
Browsers attach cookies automatically, even when a request is triggered by another site. A malicious page can make the browser submit a form to your bank, and the bank's cookie goes along. This is cross-site request forgery (CSRF). SameSite=Lax blocks the cookie on most cross-site subrequests and form POSTs, and permits it on top-level navigations such as clicking a link. Strict blocks it on all cross-site requests. Many browsers treat a cookie with no SameSite attribute as Lax, but you should set it explicitly. For state-changing actions, add a CSRF token as a second defense.
Session fixation
In a fixation attack, the attacker gets a victim to use a session ID the attacker already knows. If the server keeps that ID after login, the attacker shares the victim's session. The fix is to issue a new identifier whenever privilege changes, especially at login.
Logout and expiry
Logging out should delete the server-side record and tell the browser to remove the cookie. To remove a cookie, send it again with the same name, Domain, and Path, and with Max-Age=0.
Set-Cookie: session_id=; Max-Age=0; Path=/; HttpOnly; SameSite=LaxIf the Path or Domain differs from the original, the browser treats it as a different cookie and the original stays.
Common errors
- The cookie never arrives. Check the
Path,Domain, andSecureattributes against the URL. ASecurecookie set onhttp://is rejected by most browsers, andlocalhostis a common exception. - Cookies vanish across sites. A cookie set by
a.comis never sent tob.com. A cookie withSameSite=Nonebut noSecureis rejected. fetchignores cookies. For cross-origin requests, you must setcredentials: "include", and the server must allow it through CORS, which a later chapter covers.- Size limits. Browsers typically allow about 4 KB per cookie and cap the number per domain. Large client-side sessions can hit this.
- Cache leaks. A response with
Set-Cookieor personal content should not be stored in a shared cache. UseCache-Control: privateorno-store, as the caching chapter explains.
Cookies versus other storage
Cookies are sent on every matching request, which adds bytes and makes them suitable for authentication. localStorage is never sent automatically, and scripts can always read it, so it suits non-sensitive preferences. Tokens in an Authorization header avoid the automatic sending that causes CSRF, but you must store them somewhere script can reach.
Exercise
A login endpoint sets session_id with Set-Cookie: session_id=abc; Path=/. Name two attributes you should add and what attack each reduces.
Show answer
Add HttpOnly, so injected JavaScript cannot read the cookie through document.cookie (limits theft after XSS). Add Secure, so the browser sends it only over HTTPS and it cannot be read on the network. SameSite=Lax is also a good answer: it reduces CSRF by withholding the cookie from most cross-site requests.
Exercise
You log out by sending Set-Cookie: session_id=; Max-Age=0, but the browser still sends the old cookie. The original was set with Path=/app. Why, and what is the fix?
Show answer
The deletion has no Path, so it defaults to the path of the current request URL, which differs from /app. The browser sees a different cookie and leaves the original. Send the deletion with Path=/app, matching the original name, Path, and Domain.