Skip to content

How the browser caches a page

Working knowledgeConcept

You deploy a CSS fix, reload, and the old styles are still there. Or the Network panel says 304 and you are not sure anything was downloaded. The browser follows a small set of rules about when it may reuse a stored copy and when it must ask. Here they are, with one file traced through the cache.

01 The request that never left the browser

Open DevTools, go to the Network panel and load a site twice. On the second load many rows say (memory cache) or (disk cache) in the Size column, with a time near zero. Those files did not come from the server. Others show 304 and a few hundred bytes. Those did talk to the server, but got no body back.

Both are the browser’s HTTP cache at work. It stores responses keyed by URL, and the response headers tell it how long each one may be reused. Get the headers right and repeat visits are fast; get them wrong and users run old code for days.

02 Fresh, stale and the two questions

For every stored response the cache asks two questions:

  • Is it fresh? A response is fresh while its age is below its freshness lifetime, usually set by Cache-Control: max-age=N in seconds. A fresh copy is used with no request at all.
  • If it is stale, can I check it cheaply? If the response came with a validator (ETag or Last-Modified), the cache sends a conditional request. The server says 304 Not Modified and the stored body is reused, or sends a new 200 with the new body.

If a response has no max-age and no Expires, the cache may guess. With a Last-Modified date, browsers typically treat it as fresh for about 10% of the time since that date, as the HTTP caching standard suggests. A file last changed 10 days ago can then be reused for about a day without asking, which surprises people who set no caching headers at all.

03 One file through the cache

The server sends /app.css with Cache-Control: max-age=600 (ten minutes) and ETag: "v1". Here is the same file requested three times.

One stylesheet over half an hour
Step 1 of 8
Entry age none
Loading /app.css (times are an example)
PageHTTP cacheServerNothing sent yet
Browser HTTP cache
Empty
  • just sent or stored
  • served from the cache
  • stale, being checked
  • used as it is

A first visit at 09:00. The browser’s HTTP cache has nothing for /app.css yet.

09:00 clock

04 Validators: ETag and Last-Modified

An ETag is a label the server chooses for one version of a resource, often a hash of the content. The cache sends it back in If-None-Match; if it still matches, the answer is 304. Last-Modified works the same way with a date and If-Modified-Since, but only to the second. When both are present, ETag wins.

server.js
const http = require('node:http');
const css = 'body { color: navy; }\n';
const etag = '"v1"';
http.createServer((req, res) => {
if (req.url !== '/app.css') return res.writeHead(404).end();
if (req.headers['if-none-match'] === etag) {
res.writeHead(304, { 'ETag': etag, 'Cache-Control': 'max-age=600' });
return res.end();
}
res.writeHead(200, {
'Content-Type': 'text/css',
'Cache-Control': 'max-age=600',
'ETag': etag,
});

Play the cache by hand with curl. This is a real run against the server above, with the Date and connection headers trimmed:

Shell
curl -si localhost:3917/app.css
curl -si -H 'If-None-Match: "v1"' localhost:3917/app.css
First request
HTTP/1.1 200 OK
Content-Type: text/css
Cache-Control: max-age=600
ETag: "v1"
body { color: navy; }
With If-None-Match
HTTP/1.1 304 Not Modified
ETag: "v1"
Cache-Control: max-age=600

Frameworks often generate weak ETags such as W/"1a-abc" (Express does by default). Weak means "equivalent content", which is fine for If-None-Match.

05 The Cache-Control directives you will use

Response directives in Cache-Control
DirectiveEffect
max-age=NFresh for N seconds; reuse without asking
no-cacheStore it, but revalidate before every use
no-storeDo not store it anywhere
privateOnly the browser may store it, not a CDN or proxy
publicShared caches may store it, even for requests with credentials
s-maxage=NLike max-age, but only for shared caches such as CDNs
immutableIt will never change while fresh; do not revalidate on reload
must-revalidateOnce stale, never use it without a successful check
stale-while-revalidate=NOnce stale, serve it for N more seconds while checking in the background
no-cacheStored, always checkedEvery use costs a round trip, but usually a cheap 304. Right for HTML that must never be out of date.
no-storeNever storedEvery use downloads the full body. Right for bank statements and other private pages, wasteful elsewhere.

no-cache does not mean "do not cache". It means "do not reuse without asking". If you want nothing kept on disk, the directive is no-store.

06 When a reload really reloads

What the browser does with a fresh copy depends on how you got to the page. Browsers differ in the details; this is the typical behaviour of current Chrome and Firefox.

What each way of loading a page does with cached files
ActionThe page itselfIts CSS, JS and images
Click a link or type the URLFresh copy used, stale one revalidatedSame: fresh copies used with no request
Back or forwardMay be restored whole from the back/forward cache, or from the HTTP cache even if staleUsually from cache
Normal reload (F5, Cmd+R)Always revalidatedChrome: fresh copies used. Firefox: revalidated unless immutable
Hard reload (Shift+Cmd+R, Ctrl+Shift+R)Cache bypassed, full 200Cache bypassed; requests carry Cache-Control: no-cache
DevTools open with Disable cache tickedCache bypassedCache bypassed, only while DevTools is open

This is why "it works on my machine" is common after a deploy. You had DevTools open with Disable cache ticked, or you hard-reloaded. Your users clicked a link, and their fresh copy of last week’s app.js was used without a single request.

07 Cache forever, change the name

The way out is to stop changing files under the same URL. Build tools put a hash of the content into the file name, so every change produces a new URL. Those files can be cached for a year, because a URL never gets new content. The HTML that names them is the only thing revalidated on every visit.

Stuck for an hour
GET /app.css
Cache-Control: max-age=3600
(a fix to app.css is invisible
until each copy turns stale)
New name, new file
GET /index.html
Cache-Control: no-cache
GET /app.3f9c2a.css
Cache-Control: max-age=31536000, immutable

After a deploy, the revalidated index.html names app.7b1e04.css. That URL is not in anyone’s cache, so it is downloaded once. The old file sits unused until the cache evicts it.

08 When caching bites

index.html → Cache-Control: max-age=86400Long max-age on HTMLUsers keep the old page, which names the old asset files, for a day. No fix you ship reaches them sooner. Give HTML no-cache or a very short max-age.
GET /api/me → Cache-Control: public, max-age=60Private data in a shared cacheA CDN may store one user’s response and serve it to the next. Mark per-user responses private, or no-store if they are sensitive.
Cache-Control: no-cache # meant: never storeno-cache for secretsThe response is still written to disk. Use no-store for anything that must not persist.
GET /app.css?v=2Query strings as versionsThis does give a new URL, but bumping the number is manual and easy to forget, and some proxies have historically skipped caching URLs with queries. Content hashes in the file name are safer.
ETag: "inode-size-mtime"ETags that differ per serverIf each server behind a load balancer computes its own ETag from file metadata, the same file gets different tags and revalidations miss. Base the ETag on the content.

09 Check yourself

Question

A script was served with Cache-Control: max-age=600 five minutes ago. The user clicks a link to another page that uses it. What does the browser send?

Question

Which header makes the browser store a response but check with the server before every use?

Question

Your server answers a conditional request with 304. What travels back?

10 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?