Skip to content
devkit.notes

HTTP

Caching, CORS and security headers

Three header families that cause most production incidents: the ones that decide whether a response is reused, the ones that decide whether a browser will read it, and the ones that decide what the page is allowed to do.

1. Caching

A cache may reuse a response only if it is allowed to. The decision comes from Cache-Control, plus a validator that lets the cache revalidate instead of downloading again.

DirectiveEffectUse when
max-age=300Fresh for 300 secondsThe response changes but not per second
s-maxage=600Fresh for shared caches onlyA CDN may hold it longer than the browser
no-cacheMay store, must revalidate before reuseContent is cacheable but must be current
no-storeMust not be written to any cacheCredentials, personal data, one-time tokens
privateBrowser may store, shared cache may notPer-user HTML behind a CDN
publicAny cache may storeStatic assets with hashed names
must-revalidateNo stale use once expiredCorrectness matters more than availability
stale-while-revalidate=30Serve stale for 30 s while refreshingPerceived latency matters
immutableNever revalidate while fresh/app.9f2c1e.js

no-cache is the most misread directive in the set: it does not mean "do not cache", it means "do not reuse without asking". When the intent is "never write this to disk", the directive is no-store.

Validators are the second half. ETag is an opaque version marker; the client sends it back in If-None-Match and a match yields 304 Not Modified with no body. Last-Modified works the same way with If-Modified-Since and one-second granularity. Weak validators (W/"...") promise semantic equivalence, not byte equality.

Vary is the header people forget. If a response depends on Accept-Encoding, Accept-Language or Origin, say so, or a cache will hand one variant to everyone. Vary: * effectively disables caching; it is a correct answer for content that genuinely varies per request, and a common accident.

2. CORS

The same-origin policy stops a script on one origin from reading a response from another. CORS is the server opting out of that restriction for named origins. The response headers are the whole mechanism; there is no client configuration that can substitute for them.

HeaderDirectionMeaning
OriginrequestThe calling origin, no path
Access-Control-Allow-OriginresponseOne origin, or *
Access-Control-Allow-Credentialsresponsetrue permits cookies on cross-origin reads
Access-Control-Allow-Methodspreflight responseMethods the actual request may use
Access-Control-Allow-Headerspreflight responseRequest headers the caller may set
Access-Control-Expose-HeadersresponseResponse headers readable by script
Access-Control-Max-Agepreflight responseSeconds the preflight result may be reused

A "simple" request — GET, HEAD or POST with a content type of application/x-www-form-urlencoded, multipart/form-data or text/plain, and no custom headers — skips the preflight. Anything else triggers an OPTIONS request first, and the browser only sends the real request if that preflight is answered correctly.

Two rules that prevent most CORS bugs. First, Allow-Origin: * is incompatible with Allow-Credentials: true; a credentialed request needs an explicit origin echoed back, plus Vary: Origin so a cache does not pin one origin's answer for everybody. Second, CORS is a browser-side read restriction, not authentication — a request that the browser refuses to expose may still have been executed by the server. Protect state changes with tokens, not with origin checks.

3. Security headers

HeaderStopsBaseline value
Content-Security-PolicyInjected script and style, data exfiltrationdefault-src 'self', then widen deliberately
Strict-Transport-SecurityProtocol downgrade, cookie theft on plain HTTPmax-age=31536000; includeSubDomains
X-Content-Type-OptionsMIME sniffing that turns a text file into scriptnosniff
Referrer-PolicyLeaking paths and query strings to third partiesstrict-origin-when-cross-origin
X-Frame-OptionsClickjacking via framingDENY, or CSP frame-ancestors
Cross-Origin-Opener-PolicyWindow handle sharing with cross-origin pagessame-origin
Cross-Origin-Resource-PolicyCross-origin reads of your assetssame-origin or same-site
Permissions-PolicyCamera, microphone, geolocation and friendscamera=(), microphone=(), geolocation=()

CSP is the one worth spending time on, and the one most often deployed in a form that does nothing. default-src 'self' with no 'unsafe-inline' and no 'unsafe-eval' is a real policy; adding either back for convenience usually removes most of the protection against injected script. Inline handlers and inline <script> blocks are the usual reason teams reach for 'unsafe-inline'; moving them to external files, or using a per-response nonce, is the fix.

Report-only first. Send Content-Security-Policy-Report-Only with a report-to endpoint, watch the violations for a week, fix what breaks, then enforce. Deploying an enforced policy that nobody tested is how a login page goes blank on a Friday afternoon.

A response that gets most of this right

HTTP/2 200
content-type: text/html; charset=utf-8
cache-control: no-cache, must-revalidate
etag: "a91f4c2"
vary: accept-encoding, origin
content-security-policy: default-src 'self'; img-src 'self' data:;
  script-src 'self'; style-src 'self'; frame-ancestors 'none';
  base-uri 'none'; form-action 'self'
strict-transport-security: max-age=31536000; includeSubDomains
x-content-type-options: nosniff
referrer-policy: strict-origin-when-cross-origin
cross-origin-opener-policy: same-origin
permissions-policy: camera=(), microphone=(), geolocation=()

For a hashed asset the same server would send cache-control: public, max-age=31536000, immutable instead. The HTML is revalidated; the asset whose name changes with its content is not.

Debugging note: a header set in application code can be dropped or duplicated by a proxy. Always check what arrived at the client, with curl -sI against the public hostname, not only what the framework says it sent.