What you'll learn: By the end of this lesson you will be able to separate the two caches in a front-end build (the work your tools skip, and the files browsers keep), explain what goes into a cache key and why a missing input causes a wrong hit, use content hashes so that a deploy invalidates only what changed, and say what to measure before tuning a slow build.
Think of a bakery that bakes the same loaves every morning. A good baker does not re-mill the flour each day, and only re-labels the loaves whose recipe changed. A build does the same job, and most of the time almost nothing has changed since the last run.
The running example is the storefront of the ShopStream marketplace in a monorepo: a web app, a design-system package and an API-client package, built on every pull request and deployed on merge.
The core idea
- A cache is a promise: same inputs, same outputs. If the key is missing an input, the cache returns a wrong answer quickly.
- There are two separate caches. Build-time caches save your team's minutes; browser caches save your users' bytes. They meet at one place: the file name of the output.
- Measure before you tune. Time a build with a cold and a warm cache and see which step dominates.
The bundler itself is the subject of the bundlers and build tooling lesson in this module; this lesson is about reuse.
Figure 1. Two caches, one pipeline
How to read this: on the left, the build cache lets the build skip work whose inputs did not change. On the right, the browser cache lets users skip downloads whose file names did not change. The hashed file name in the middle connects the two.
Build-time caching: skip the work you already did
Caches stack, from small and local to large and shared.
- Inside the tool. TypeScript's
incrementaloption saves information about the last compilation in.tsbuildinfofiles, which the documentation says can be safely deleted;compositelets tools, including--buildmode, quickly decide whether a project has been built. The Vite development server caches pre-bundled dependencies innode_modules/.viteand redoes that step only when the lockfile, patches folder, relevantvite.configfields orNODE_ENVchange. webpack's documentedcachedefault is off in production mode and in-memory in development mode, at the time of writing. - Across tasks in a monorepo. A task runner hashes a task's inputs and, on a match, replays stored outputs and logs. Turborepo stores results in
.turbo/cacheand caches only the file outputs you declare inoutputs. Nx hashes source files, workspace configuration, versions of external dependencies, runtime values such as operating system and CPU architecture, and command-line arguments. - Across CI runs. A CI runner starts empty. With GitHub Actions, a cache hit needs an exact key match, an existing cache cannot be changed (you create one under a new key), entries not accessed for over 7 days are removed, and the default limit is 10 GB per repository.
- Across machines. Remote caching shares the task cache with CI and teammates; decide who may write to it.
Figure 2. A hit or a miss
files + lockfile + tool + declared env"] --> B{"Key in cache?"} B -->|"yes"| C["Restore outputs and logs
(task does not run)"] B -->|"no"| D["Run the task"] D --> E["Store declared outputs
under the key"] E --> F["Outputs available"] C --> F
How to read this: the left branch is the fast path. The risk is in the first box: anything that changes the output but is not in the key makes the "yes" branch wrong.
Illustration 1: the minimal example
A task key is a hash over everything that should change the result. This toy model (not Turborepo's or Nx's algorithm) shows the behaviour. Run in Node:
import { createHash } from "node:crypto";
function taskKey({ files, lockfile, node, env }) {
const h = createHash("sha256");
for (const name of Object.keys(files).sort()) h.update(`${name}\0${files[name]}\0`);
h.update(`lock\0${lockfile}\0node\0${node}\0`);
for (const name of Object.keys(env).sort()) h.update(`env:${name}=${env[name]}\0`);
return h.digest("hex").slice(0, 12);
}
const base = { files: { "src/app.ts": "export const a = 1;" }, lockfile: "lock-v1", node: "v26.13.1", env: { VITE_API: "https://api.example.test" } };
const rows = [
["same inputs", base],
["edited source", { ...base, files: { "src/app.ts": "export const a = 2;" } }],
["new lockfile", { ...base, lockfile: "lock-v2" }],
["declared env changed", { ...base, env: { VITE_API: "https://api.staging.example.test" } }],
];
const seen = new Set([taskKey(base)]);
console.log("first run:".padEnd(22), taskKey(base), "(miss, then stored)");
for (const [label, inputs] of rows) {
const key = taskKey(inputs);
console.log((label + ":").padEnd(22), key, seen.has(key) ? "HIT" : "miss");
seen.add(key);
}
Output, from running it in Node 26.13.1:
first run: 5e1b1b587cd7 (miss, then stored)
same inputs: 5e1b1b587cd7 HIT
edited source: 057ba441522a miss
new lockfile: 04d365294504 miss
declared env changed: 7ad0e330023c miss
A variable the build reads but the key omits would not change the key, which is how a cache serves a build made for another environment. Turborepo puts environment values in the hash through variables you list, and does not cache outputs you do not declare.
Output caching: content-hashed file names
Browsers cache by URL, so the reliable way to keep a long-lived cache correct is to put a version into the name. MDN calls this cache busting: with hashed file names you can add a long max-age and immutable, because the content at that URL never changes and new content gets a new URL. See HTTP Caching and CDN and Edge Caching.
Bundlers do this for you. In webpack, [contenthash] adds a hash based on the asset's content. Vite's documentation says referenced assets get hashed names in the production build, files in public are copied as-is without hashing, and build.manifest maps non-hashed names to hashed ones.
Illustration 2: the realistic example
Because the content is hashed, a change ripples to whatever refers to the file by name. A three-file build where the entry imports the app file by its hashed name. Run in Node:
import { createHash } from "node:crypto";
const h = (text) => createHash("sha256").update(text).digest("hex").slice(0, 8);
function build(sources) {
const files = {};
for (const [name, code] of Object.entries(sources)) files[`${name}.${h(code)}.js`] = code;
const appFile = Object.keys(files).find((f) => f.startsWith("app."));
const entry = `import "./${appFile}";`;
files[`main.${h(entry)}.js`] = entry;
return Object.keys(files).sort();
}
const v1 = build({ vendor: "react code", app: "checkout v1" });
const v2 = build({ vendor: "react code", app: "checkout v2" });
console.log("build 1:", v1.join(" "));
console.log("build 2:", v2.join(" "));
console.log("unchanged:", v1.filter((f) => v2.includes(f)).join(" "));
Output, from running it in Node 26.13.1:
build 1: app.9c14cbb7.js main.3100ce6a.js vendor.6e917aa6.js
build 2: app.3f03f33b.js main.3cbfa7a3.js vendor.6e917aa6.js
unchanged: vendor.6e917aa6.js
Editing the app renamed it and the entry that points at it; the vendor file kept its name, so returning visitors keep it cached. This is why webpack's caching guide recommends a separate vendor chunk for third-party code such as react, and runtimeChunk: 'single' so the entry's boilerplate does not change its hash on every build. See Code Splitting, Lazy Loading and Tree Shaking.
Illustration 3: a failure
webpack's guide warns that a visitor running an old entry chunk may request an old async chunk name that no longer exists, and recommends keeping previous build assets available and handling failed chunk loads, for example with a reload guarded against loops.
Figure 3. A deploy while a tab is open
How to read this: content hashing protects caches, not open tabs. Old tabs hold old names, so the deploy process, not the bundler, has to keep them working.
Trade-offs
| Choice | Gain | Cost |
|---|---|---|
| Task cache in a monorepo | Unchanged packages are skipped | Every input must be declared |
| CI cache restore | Fresh runners start warm | Key design, size and eviction |
| Remote cache | Teammates and CI share results | Write access becomes a security question |
Hashed names with long max-age |
Returning users re-download only what changed | More files; old tabs may ask for removed ones |
Build it
This lesson has no lab. The two Node snippets are plain Node, and their output is shown as run. The tool behaviours described (TypeScript, Vite, webpack, Turborepo, Nx, GitHub Actions) come from their documentation and were not run here; defaults can change between versions.
In practice: a slow pull-request pipeline
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
The ShopStream storefront monorepo runs lint, type-check, test and build on every pull request, and authors wait about 14 minutes (illustrative) even for a copy change. The unchanged design-system package is rebuilt every time, and every deploy makes returning shoppers download the whole bundle again.
Starting architecture
Figure 4. Everything rebuilt, nothing cached
How to read this: the two warning boxes are the two problems. The runner repeats every task, and unstable output names defeat the browser cache.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Bigger CI machines | Raw speed | Money | Same work, repeated |
| Task cache with declared inputs and outputs | Skips unchanged packages | Config per task | A missing input gives a wrong hit |
Content hashes, vendor chunk, long max-age |
Returning users keep unchanged files | Old assets kept after deploy | Old tabs fail if files vanish |
The decision
| Field | Decision record |
|---|---|
| Context | Slow pull-request pipeline; every deploy invalidates every visitor's cache. |
| Decision | Add a task cache with declared inputs, outputs and variables; key the CI cache on the lockfile; hash names by content; split vendor code; keep the previous build's assets for a window after each deploy. |
| Consequences, good | Unchanged packages are skipped; returning visitors re-download only changed files. |
| Consequences, bad | Inputs must be maintained; the deploy keeps two builds of assets. |
| Revisit when | The bundler changes, or cache hit rate drops. |
Rollout and verification
- Measure first: record time per step, cold and warm.
- Enable the build cache and compare a replay with a clean build of the same commit.
- Change a declared variable in a branch and confirm a miss.
- Check two builds: unchanged vendor files keep their names.
The 2 a.m. failure
A build cached on a commit whose key did not list VITE_API is promoted. The staging URL is baked into the production bundle, and checkout calls the wrong host.
First three checks: (1) compare the bundle's baked values with the intended environment; (2) compare the task's declared inputs with what the build reads; (3) check the cache key of the promoted artifact. Mitigation: rebuild with the cache bypassed and redeploy. Follow-up: list every variable the build reads, and keep environment-specific values out of the artifact (see Runtime Configuration and Environments in this module).
Architect's notes
- Declare inputs like a contract. If a build reads it, the key contains it.
- Cache the slow step, and treat the cache as disposable: the build must be correct without it.
Common mistakes
- Tuning before measuring.
- A key that ignores the lockfile or a variable the build reads.
- No declared
outputs, so files are never stored. - Deleting the previous deploy's assets at once, breaking open tabs.
- A long
max-ageon a name that is not hashed, such as files copied frompublic.
Key takeaways
- Build caches reuse work by key; browser caches reuse files by URL; the hashed file name joins them.
- A cache key must contain every input that changes the output.
- Content hashes limit invalidation to what changed, but ripple to referrers.
- Keep old assets briefly after a deploy, and handle failed chunk loads.
Practice exercises
Exercise 1: Starter (30 min). Run the first Node snippet, then add a row that changes only a comment in a source file and explain whether it should be a hit.
Exercise 2: Intermediate (2 hours). Extend the second snippet so app imports a util file by hashed name. Predict which names change when util changes, then run it.
Exercise 3: Advanced (half day). List every variable and config file a build you know reads, and decide which belong in its cache key.
Related reading
In this course:
- HTTP Caching: the headers that make hashed names pay off.
- CDN and Edge Caching: where the hashed files are served from.
- Caching Across the Stack: how the layers fit together.
- Monorepos and Shared Libraries: where task caches pay off.
Official documentation
- webpack: Caching and Cache configuration: content hashes, runtime and vendor chunks, the filesystem cache.
- Vite: Dependency Pre-Bundling and Static Asset Handling: the development cache and hashed asset names.
- Turborepo: Caching and Nx: Cache task results: what goes into a task hash.
- GitHub Docs: Dependency caching: keys, restore keys and eviction.
- TypeScript: TSConfig Reference:
incremental,compositeandtsBuildInfoFile. - MDN: Cache-Control:
immutableand cache busting.