Sessions and authorization
Authenticate every request
Resolve a session cookie into trusted identity context and reject missing, expired, revoked, or malformed sessions consistently.
8 minute lesson
Each protected HTTP request is independent. Middleware must validate the presented session before handlers rely on an identity.
Read the cookie, validate the opaque identifier’s encoding and length, hash it if the stored lookup key is hashed, load the server record, check expiry and revocation, and attach a minimal identity context. Authority comes from the server record, never by parsing claims from an opaque token. Do not place session tokens in URLs or logs.
Keep the middleware result small:
type AuthContext = {
userId: string
sessionId: string
authenticatedAt: Date
}
Do not copy roles or account state into long-lived request-independent memory. Authorization-relevant data can change. Load it at the correct boundary or include a version that forces stale sessions to refresh.
Distinguish absence from infrastructure failure. A missing or invalid session normally becomes 401 Unauthorized. A session-store outage is a server failure; treating it as anonymous can accidentally expose a route designed for both public and private results.
Run authentication before reading protected request data or starting expensive work. The handler should receive either a trusted context or no execution at all.
Cache carefully. A shared HTTP cache must never serve one authenticated user’s response to another. Mark private responses correctly and include identity in any application cache key.
Add middleware to the Books API and protect create, update, delete, and private list routes. Revoke a session between two requests and confirm no protected handler runs on the second one.
Lesson completed