← All lessons
How HTTP caching works
Fetch, reuse, then revalidate
Browser
Cache
Server
browser-cache.js
// what the browser cache does with each requestasync function load(url) { const hit = cache.get(url); if (!hit) return fetch(url); if (hit.age < hit.maxAge) return hit.body; const res = await fetch(url, { headers: { "If-None-Match": hit.etag }, }); if (res.status === 304) return hit.body; return res.body;}server.js
app.get("/app.css", (req, res) => { const etag = `"${hash(css)}"`; if (req.headers["if-none-match"] === etag) { return res.status(304).end(); // no body } res.set("Cache-Control", "max-age=60"); res.set("ETag", etag); res.send(css);});Pick a Cache-Control header then move the clock
The page asks for app.css again
request
response
downloaded
you get
browser-cache.js
// header: the Cache-Control the file came withswitch (header) { case "max-age=60": if (age < 60) return cached.body; return revalidate(cached); case "no-cache": return revalidate(cached); case "no-store": return fetch(url); // keeps no copy case "max-age=31536000, immutable": return cached.body;}browser-cache.js
async function revalidate(cached) { const res = await fetch(url, { headers: { "If-None-Match": cached.etag }, }); if (res.status === 304) return cached.body; return res.body; // 200 with the new file}Hashed file names ship updates past a year-long cache
app.css
Build output
hash
file
index.html
A returning visitor, with last week's files cached for a year
The HTML itself can't be cached for a year. It uses no-cache, so it always sees the newest names
build.js
// at build time, name each file after its contentconst hash = contentHash(css).slice(0, 8);const name = `app.${hash}.css`;write(`dist/assets/${name}`, css);html = html.replace("app.css", name);server.js
// hashed files never change, so keep them a yearapp.use("/assets", express.static("dist/assets", { maxAge: "1y", immutable: true,})); // the HTML always checks back, so it sees new namesapp.get("/", (req, res) => { res.set("Cache-Control", "no-cache"); res.sendFile("dist/index.html");});Topics
Next: How a CDN works
Open lesson