How does HTTP caching work for frontend assets? Explain Cache-Control, ETags and cache busting.
Cache-Control directives
max-age=N: the response is fresh for N seconds; no request is made at all.no-cache: may be stored, but must be revalidated with the server before each use.no-store: never store (sensitive data).public/private: whether shared caches (CDNs) may store it;privatefor per-user responses.immutable: will never change, so the browser should not revalidate even on reload.s-maxage: freshness for CDNs only.stale-while-revalidate=N: serve stale while fetching a fresh copy in the background.
Validation
When a response is stale, the browser sends If-None-Match (with the ETag) or If-Modified-Since. If nothing changed, the server replies 304 Not Modified with no body.
The standard strategy for SPAs
- Build tools (Vite, webpack) put a content hash in file names:
app.3f9a1c.js. Serve them withCache-Control: public, max-age=31536000, immutable. A change produces a new file name (cache busting). - Serve
index.htmlwithCache-Control: no-cacheso users always get the latest list of hashed files. - API responses: usually
private, no-cacheor a shortmax-age, with ETags.
Service workers
Add a programmable cache in front of the network: cache-first for hashed assets, network-first for HTML, stale-while-revalidate for some API data (Workbox makes these one-liners). Remember to version caches and handle updates.
Example
GET /assets/app.3f9a1c.js
Cache-Control: public, max-age=31536000, immutable
GET /index.html
Cache-Control: no-cache
ETag: "v42"
# later, revalidation
GET /index.html
If-None-Match: "v42"
→ 304 Not Modifiedlocation /assets/ {
add_header Cache-Control "public, max-age=31536000, immutable";
}
location = /index.html {
add_header Cache-Control "no-cache";
}Follow-up questions interviewers ask
Try answering each one before you open it.
Users see a broken page after a deploy. Why?
They have an old index.html (cached too long) pointing to hashed chunks that were deleted, or a lazily loaded chunk from the previous build is requested after the deploy. Keep old assets for a while after deploying, serve index.html with no-cache, and catch chunk load errors (vite:preloadError) by reloading the page once.