CodePark/ questions / HTTP caching & CDNs
START PRACTICINGPRACTICE
Frontend question · Browser & web performance › HTTP caching & CDNs

What caching headers would you use for a single-page app's index.html versus its JS and CSS bundles? Explain cache busting with hashed filenames.

Cache the hashed JS and CSS files for a year, and make index.html revalidate every time.

Hashed files: build tools put a content hash in asset file names, like app.3f9a1c.js. When the content changes, the name changes. So the URL is new, and no cache can serve the old file. This is cache busting. It means the assets can be cached for a very long time: Cache-Control: public, max-age=31536000, immutable.

The HTML: the HTML that points to those files can't have a hashed name, so it must stay fresh. Use Cache-Control: no-cache. The browser stores it, but revalidates it with an ETag each time. A very short max-age also works. After a deploy, the browser gets the new HTML, and that points to the new hashed files.

Why both parts matter:

  • If you cached the HTML for long, users would keep loading old bundles.
  • If you didn't hash the assets, a long max-age would serve old code.
  • A content hash in the file name changes the URL whenever the content changes.
  • Hashed assets get one year of max-age plus immutable.
  • The HTML gets no-cache or a short max-age.
  • The HTML is the entry point, and it points to the new assets.