Caching Strategies
🎯 Introduction
On a user's first visit, the browser downloads HTML, JavaScript, CSS, images, and other resources. Must it download them all again on the next visit? Doing so slows loading, increases server load, and wastes bandwidth. HTTP caching solves this by storing downloaded resources locally in the browser for reuse.
By the end of this article, you will be able to:
- Explain cache freshness and revalidation, and how they work together.
- Read the
Cache-Control,Expires,ETag, andLast-Modifiedresponse headers. - Understand why build tools add content hashes to JavaScript and CSS filenames.
- Design a sensible caching policy for your project.
🧱 Why Caching Matters
Imagine borrowing a library book and taking it home. To read it again the next day, you open the copy at home rather than returning to the library. Browser caching works similarly: once downloaded, a resource is stored locally, and subsequent requests first check for a usable local copy.
Without caching, every page visit downloads all resources again, requiring more network requests and longer waits. With caching, repeat visits reuse local copies. Many requests never need to reach the network, making loading faster and reducing server load.
HTTP caching has two stages, checked in order:
- Fresh cache reuse: if the local copy has not expired, use it without sending a request.
- Cache revalidation: if the local copy has expired, ask the server whether it has changed. Reuse it if unchanged; otherwise, download the new content.
Let's examine how each stage works.
🧱 Fresh Cache Reuse: No Request Until Expiration
The central idea is simple: while a cached response is fresh, the browser uses its local copy without contacting the server.
Expires: The Older Approach
Expires is a response header from HTTP/1.0. It tells the browser that a resource remains fresh until a specified time:
HTTP/1.1 200 OK
Content-Type: text/css
Expires: Wed, 21 Jul 2027 02:45:43 GMT
After reading Expires, the browser remembers the expiration time and uses the local copy for requests made before that time.
This has a clear drawback: it depends on the user's system clock. If the clock is incorrect, perhaps because it was manually advanced, expiration checks can be wrong. More reliable approaches have largely replaced it, and it now mainly serves compatibility needs.
Cache-Control: The Standard Approach
The HTTP/1.1 Cache-Control response header uses a relative duration instead of an absolute time, avoiding dependence on the user's local clock:
HTTP/1.1 200 OK
Content-Type: text/css
Cache-Control: max-age=31536000
max-age=31536000 means the resource remains fresh for 31,536,000 seconds, or one year, from the response. The browser effectively records the receipt time plus max-age. During that period, subsequent requests use the local cache without going to the network.
When both headers are present, Cache-Control takes precedence over Expires. Modern projects typically configure only Cache-Control.
For now, remember that a valid max-age=seconds allows fresh cache reuse. Two other common directives prevent this direct reuse:
no-cache: despite its name, this does not prohibit storage. It requires the browser to confirm the response with the server before each reuse. The next section explains this revalidation process.no-store: this prohibits caching entirely, so the resource must be downloaded each time.
(disk cache) or (memory cache) in the Size column and a gray 200 in the Status column. This is a convenient way to check whether cache reuse is working.🧱 Cache Revalidation: Ask After Expiration
An expired local copy cannot be reused directly, but that does not mean its content has changed. Cache revalidation sends the cached response's validator to the server. If the content is unchanged, the browser keeps using its local copy; otherwise, it downloads a new one.
ETag and If-None-Match
An ETag is an identifier generated by the server for a resource. Think of it as a fingerprint that changes when the content changes. The server includes it in the initial response:
HTTP/1.1 200 OK
Content-Type: text/css
ETag: "abc123"
After expiration, the browser sends this fingerprint in the If-None-Match request header:
GET /style.css HTTP/1.1
Host: example.com
If-None-Match: "abc123"
The server compares the fingerprint. If the content is unchanged, it returns 304 Not Modified, with headers but no response body. The browser then reuses its local copy:
HTTP/1.1 304 Not Modified
ETag: "abc123"
If the content has changed, the server returns 200 with the new content and a new ETag. A 304 response contains no body, so it transfers much less data than downloading the whole file again.
Last-Modified and If-Modified-Since
This alternative pair uses a modification time instead of a fingerprint. The server includes the resource's modification time in its response:
HTTP/1.1 200 OK
Content-Type: text/css
Last-Modified: Wed, 21 Jul 2026 02:45:43 GMT
After expiration, the browser sends that time back to the server:
GET /style.css HTTP/1.1
Host: example.com
If-Modified-Since: Wed, 21 Jul 2026 02:45:43 GMT
If the resource has not changed since that time, the server also returns 304 Not Modified.
ETag Takes Precedence over Last-Modified
When both validators are present, the server gives ETag precedence. Time-based validation has limited precision: Last-Modified is accurate only to the second, so two changes within one second cannot be distinguished. A file may also be saved again without changing its content, updating its timestamp and causing an unnecessary download. A content-based ETag avoids that problem.
The revalidation process is: after expiration, ask the server; reuse the cached response on 304, and download new content only when it changes.
⚡ Fresh Cache Reuse vs. Revalidation
The two mechanisms serve different purposes:
| Comparison | Fresh cache reuse | Cache revalidation |
|---|---|---|
| When used | While the cached response is fresh | After the cached response expires |
| Network request | None; use the local copy | Ask the server to validate the response |
| Response headers | Cache-Control, Expires | ETag, Last-Modified |
| Request headers | None | If-None-Match, If-Modified-Since |
| Server response | None; no request is sent | 304 if unchanged, 200 if changed |
| Data transferred | 0 | Headers only for 304, without the resource body |
| Typical status | 200 (from cache) | 304 Not Modified |
Fresh cache reuse avoids the entire request, but updates remain unavailable until expiration. Revalidation contacts the server each time, ensuring new content is retrieved promptly. Real projects combine both approaches, as the next section shows.
🛠 Practical Caching for Static Assets
How should you apply this in a real project? The key is to treat different resources differently.
Hashed Filenames: Safe Long-Term Caching
Modern build tools such as webpack and Vite add a content hash to JavaScript and CSS filenames, for example app.a1b2c3d4.js. Change even one byte and the hash changes, producing a new filename such as app.e5f6g7h8.js.
This gives us a useful property: changed content has a new filename, so the browser downloads it as a new resource. The old cached copy no longer applies, without any manual intervention.
For hashed files, you can therefore set a long max-age. This is a server response header; the next section shows how to configure it:
Cache-Control: max-age=31536000
Repeat visits reuse the local copy for a year, while new releases automatically trigger downloads of resources with new filenames. The Vite course explains hashed filenames in more detail.
The HTML Entry Point: Keep It Up to Date
HTML is the page's entry point and references the hashed JavaScript and CSS URLs. Cache it for a year and users keep receiving old HTML that points to old JavaScript, preventing them from receiving the new release.
Use revalidation or a short freshness lifetime for the HTML entry point so users receive updates promptly:
Cache-Control: no-cache
no-cache requires confirmation before each reuse. An unchanged response returns 304 and reuses the local copy at low cost. A changed response supplies new HTML, which references the new hashed JavaScript and CSS. This completes the update chain.
Configuring Cache Headers with Express
With the policy established, implementation is straightforward. This minimal Express example, tested with Node.js v22 and Express v4, gives hashed static assets a long freshness lifetime and requires revalidation for HTML:
const express = require('express');
const app = express();
// Hashed static assets: long-lived fresh cache reuse
app.use(
'/assets',
express.static('dist/assets', {
maxAge: '365d', // Equivalent to max-age=31536000
}),
);
// HTML entry point: revalidate with the server before each reuse
app.use(
express.static('dist', {
setHeaders(res, filePath) {
if (filePath.endsWith('.html')) {
res.setHeader('Cache-Control', 'no-cache');
}
},
}),
);
app.listen(3000);
If Express static file hosting is unfamiliar, see the relevant sections of the Express course. Here, focus on the maxAge and setHeaders options.
Cache-Control is a response header returned by the server. Configure it on the server hosting the project, such as Nginx, a CDN, or Express. Frontend JavaScript cannot set it for these responses.❓ Questions and Answers
Q1: Does refreshing the page still use a fresh cached response?
A normal refresh (F5) usually still uses the cache. A hard reload (Ctrl/Cmd + Shift + R) bypasses the local cache and requests resources from the server, which is useful for debugging caching issues.
Q2: What is the difference between no-cache and no-store?
no-cache allows storage but requires server validation before each reuse, effectively going straight to revalidation. no-store prohibits storage and requires a fresh download each time. It is commonly used for responses containing sensitive information.
Q3: Why keep Last-Modified when ETag exists?
Last-Modified mainly provides a fallback and compatibility. When both validators are present, ETag takes precedence. In cases where a coarse modification time is sufficient, Last-Modified may be enough.
Q4: Why use no-cache for HTML instead of max-age=0?
Their effects are similar: both require checking with the server before reuse. no-cache communicates that intent more directly and is common in modern projects.
Q5: Why might users keep receiving an old JavaScript version?
A common cause is cached HTML that still references an old hashed JavaScript URL. Check whether the HTML response requires revalidation, and add Cache-Control: no-cache if needed.
Q6: Can frontend JavaScript configure these cache response headers?
No. The server supplies response headers when returning resources. Frontend JavaScript does not control that stage; configure them on the hosting server, such as Nginx or a CDN.
🧪 Exercises
Exercise 1: Extend the Express example with a rule that caches images for 30 days. Start the server and use the Chrome DevTools Network panel to check that each resource has the expected Cache-Control response header.
const express = require('express');
const app = express();
app.use(
express.static('dist', {
setHeaders(res, filePath) {
if (filePath.endsWith('.html')) {
res.setHeader('Cache-Control', 'no-cache');
}
// Write your code here: set max-age to 30 days (2592000 seconds) for files ending in .png or .jpg
},
}),
);
app.listen(3000);
Exercise 2: Open a frequently visited website, refresh it with the Chrome DevTools Network panel open, and inspect the Status and Size columns. Find one fresh cache hit and one 304 response. Which cache-related headers does each response include?
🎉 You now understand HTTP caching strategies! You can explain fresh cache reuse and revalidation, and apply a practical policy: long-lived caching for static assets and revalidation for HTML. Next, we will optimize build output to improve performance at the source.
