intermediate

Headers and cookies

Use headers and cookies for content negotiation, cache directives, auth context, security policies, session state, and browser constraints.

Headers negotiate representation, caching, security, and tracing. Common request headers: `Accept`, `Authorization`, `Content-Type`, `If-None-Match`, `X-Request-Id`. Response headers: `Content-Type`, `Cache-Control`, `ETag`, `Set-Cookie`, `Location`.

Cookies carry session identifiers or preferences. Attributes matter: `HttpOnly` blocks JavaScript access; `Secure` requires HTTPS; `SameSite` controls cross-site sending; `Domain` and `Path` scope the cookie; `Max-Age` or `Expires` set lifetime.

					Set-Cookie: sid=abc; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=3600
				

In Node, prefer setting cookies through framework helpers that encode attributes correctly. Treat `Authorization` headers and cookies as secrets in logs.

On interviews: explain content negotiation, why `Vary` matters for caches, cookie scoping bugs across subdomains, and header size limits (~8 KB total in many servers).

Common pitfalls: logging full Cookie or Authorization headers; wildcard Domain on parent sites; missing Secure on production cookies.

The trade-off is balancing simplicity, performance, safety, and operability — name which axis you optimized and what cost you accepted.

Checklist:

  • Know negotiation and cache-related headers.
  • Set cookie security attributes deliberately.
  • Propagate request IDs for tracing.
  • Redact sensitive headers in logs.