Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 38 ยท Optimization and Caching

Long-Term Caching with Content Hashes

Make returning visitors download less: webpack contenthash file names, deterministic module ids, runtimeChunk, cache headers, and the persistent build cache.

Browsers and CDNs love files that never change. If app.js can be cached for a year, a returning visitor downloads nothing. The difficulty is that you do change your code, and visitors must get the new version immediately. The classic answer is cache busting: put a fingerprint of the file's content into its name. When the content changes, the name changes, the old cached file is simply never requested again, and the new one is fetched.

Webpack supports this with [contenthash] in file names. This lesson explains how it works, why hashes sometimes change when you did not touch the code, and the settings that make them stable. It also covers webpack's separate, build-time persistent cache, which speeds up rebuilds.

Webpack cannot run on this site. Configuration is read-only; the runnable examples are Node.js stand-ins that compute real SHA hashes of tiny "chunks" so you can see what makes a fingerprint change.

Hash types

Webpack offers several placeholders for output file names:

Placeholder Based on Use
[hash] The whole compilation Avoid: everything changes on any edit.
[fullhash] Same as [hash] in webpack 5 Avoid for the same reason.
[chunkhash] A chunk and its modules Fine for JS, but also changes when extracted CSS changes.
[contenthash] The file's own content Best choice for caching.
JavaScript
// webpack.config.js (read-only example)
module.exports = {
  mode: 'production',
  output: {
    filename: '[name].[contenthash:8].js',
    chunkFilename: '[name].[contenthash:8].chunk.js',
    assetModuleFilename: 'assets/[name].[contenthash:8][ext]',
    clean: true,
  },
  optimization: {
    moduleIds: 'deterministic',
    runtimeChunk: 'single',
    splitChunks: { chunks: 'all' },
  },
};

:8 shortens the hash to eight characters, which is plenty. clean: true removes old files from the output folder before each build.

A stand-in for content hashing

The following stand-in builds three tiny chunks and prints their fingerprints. Then it edits only the app code and shows which file names change. Real webpack uses its own hash function (md4 or xxhash64 by default, configurable with output.hashFunction), but any content hash behaves like this.

Node.js Stand-in: which fingerprints change after an edit?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Only the app file gets a new name. The vendor and shared files keep their names, so browsers use their cached copies. That works only while the vendor chunk's content stays identical, which is where the next problems come in.

Why hashes change when they should not

Three culprits recur.

1. The runtime lives in the entry chunk

Webpack's bootstrap code contains a map from chunk ids to file names. Add or rename any chunk and the map changes, and so does the entry file. The fix is optimization.runtimeChunk: 'single', which moves the runtime into runtime.[hash].js, a tiny file that changes often but costs almost nothing. You can inline it in the HTML with HtmlWebpackPlugin plus InlineChunkHtmlPlugin to save a request.

2. Module ids shift

Webpack gives each module a numeric or string id. If ids are assigned in order of discovery, adding one module can renumber others and change many chunks. Webpack 5 defaults to moduleIds: 'deterministic', which derives ids from the module's path, so unrelated edits do not renumber it. Keep it that way. (Use 'named' only in development for readable output.)

3. Vendor code is not separated

If your dependencies are inside the same chunk as your code, every release changes that chunk. Use splitChunks to extract node_modules into a stable vendor chunk.

Node.js Stand-in: unstable ids ruin caching

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

With position-based ids the vendor chunk changes although react and utils did not. With name-based ids it stays identical.

Serving the files: Cache-Control

Fingerprinted names are only half the story; the server must say they can be cached for a long time:

NGINX
# fingerprinted assets: one year, immutable
location /assets/ {
  add_header Cache-Control "public, max-age=31536000, immutable";
}
# the HTML that references them: always revalidate
location = /index.html {
  add_header Cache-Control "no-cache";
}

The HTML must never be cached for long, because it holds the names of the current files. With HtmlWebpackPlugin each build writes an HTML file that points at the new hashed names.

One more risk: after a deploy, someone with an old HTML page may request a chunk that is gone. Keep the previous release's files on the server for a while, and see how to retry failed chunk loads.

The persistent build cache

A different cache exists inside webpack itself. Setting cache: { type: 'filesystem' } stores compiled modules on disk between runs, so the second build is much faster, often several times.

JavaScript
module.exports = {
  cache: {
    type: 'filesystem',
    buildDependencies: {
      config: [__filename],   // invalidate when the config changes
    },
  },
};

Do not confuse the two: the persistent cache speeds up your builds and never reaches users; content hashes speed up your users' browsing.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which placeholder is the best choice for long-term caching of a chunk's file name?

    [contenthash] derives from the file's own content, so unchanged files keep their names.
  2. 2. Why use runtimeChunk: 'single'?

    The runtime embeds the chunk file-name map and changes whenever chunks change. Isolating it protects the other files.
  3. 3. What Cache-Control policy suits index.html that references hashed assets?

    The HTML holds the current file names, so it must be revalidated. The hashed assets themselves can be cached for a year.
  4. 4. What does cache: { type: 'filesystem' } improve?

    It stores compilation results on disk for faster subsequent builds; it does not affect what users download.

Summary

  • Put [contenthash] in file names so unchanged files keep their URLs.
  • Stabilize hashes with runtimeChunk: 'single', moduleIds: 'deterministic' and a separate vendor chunk.
  • Serve hashed files with long immutable caching and the HTML with no-cache.
  • The filesystem cache speeds up builds; content hashes speed up users.

Next: Bundle Analysis and Performance Budgets