APIs · Intermediate · 24 min
Cache API responses with Cache-Control and ETags
By Padding · Updated 18 Nov 2026
Debian (node:26 image) · Node.js 26.13.1 · curl
You will give each endpoint of a small Node.js 26 API its own Cache-Control policy, add ETag and Last-Modified validators that answer 304 Not Modified, compress large responses with the right Vary header, and finish with a script that checks the policy for every endpoint.
On this page
Every response your API sends can carry instructions for the caches between your server and the person using it: the browser or app on their phone, a CDN in front of your servers, sometimes a company proxy. Good instructions mean repeat requests cost almost nothing. Missing instructions leave each cache to guess, and a guess about a response that holds someone's personal data is a guess you do not want made.
HTTP gives you two tools. Cache-Control says who may keep a copy and for how long. Validators (ETag and Last-Modified) let a client that already holds a copy ask "has this changed?" and get back an empty 304 Not Modified when it has not. You will use both on a small library API built with Node's own node:http module, so there is nothing to install from npm:
GET /api/books: the public catalogue, the same for everyone.GET /api/me/settings: one reader's preferences.GET /api/me/loans: one reader's borrowed books, personal data.POST /api/me/loans: borrow a book.
You build the caching in one small module, cache.mjs, and rewrite it as you go. Each step adds one idea and shows the headers it produces with curl. The last step turns the decisions into a policy table and a script that checks it.
This matters most where data is paid for by the megabyte. On prepaid mobile data, common across much of Africa, a 304 that replaces a 20 KB body saves the reader money, and a low-end Android phone skips parsing JSON it already has.
Step 1 · Build the API with no caching headers
Check your Node.js version. This tutorial was checked on 26.13.1:
node --versionThe output starts with v26.. Create a demo folder and mark it as an ES module project:
mkdir -p ~/api-cache-demo
cd ~/api-cache-demo
cat > package.json <<'JSON'
{ "name": "api-cache-demo", "private": true, "type": "module" }
JSONCreate data.mjs. It builds a catalogue of 200 book copies in memory, with a date for the last change, and keeps each reader's loans in a Map. Some names contain letters outside ASCII, which matters later because the body length is counted in bytes, not characters:
cat > data.mjs <<'JS'
const titles = [
['Things Fall Apart', 'Chinua Achebe', 1958],
['Weep Not, Child', "Ngũgĩ wa Thiong'o", 1964],
['So Long a Letter', 'Mariama Bâ', 1979],
['Season of Migration to the North', 'Tayeb Salih', 1966],
['Nervous Conditions', 'Tsitsi Dangarembga', 1988],
['The Famished Road', 'Ben Okri', 1991],
['Half of a Yellow Sun', 'Chimamanda Ngozi Adichie', 2006],
['Aké: The Years of Childhood', 'Wole Soyinka', 1981],
];
export const catalogue = {
updatedAt: new Date('2026-11-02T09:30:00Z'),
books: Array.from({ length: 200 }, (_, i) => {
const [title, author, year] = titles[i % titles.length];
return { id: i + 1, title, author, year, copy: Math.floor(i / titles.length) + 1, available: true };
}),
};
const loans = new Map();
export function loansFor(user) {
if (!loans.has(user)) loans.set(user, []);
return loans.get(user);
}
JSCreate cache.mjs. For now its send function writes JSON with a type and a length and nothing else. The routes already pass it a policy name and a date, which it ignores until the next steps:
cat > cache.mjs <<'JS'
export function send(req, res, status, payload) {
const body = Buffer.from(JSON.stringify(payload));
res.writeHead(status, {
'content-type': 'application/json; charset=utf-8',
'content-length': body.length,
});
res.end(req.method === 'HEAD' ? undefined : body);
}
JSCreate server.mjs. The X-Demo-User header stands in for your real session or token check, so the demo can tell readers apart without any secrets. Never trust a header like this in a real API:
cat > server.mjs <<'JS'
import { createServer } from 'node:http';
import { catalogue, loansFor } from './data.mjs';
import { send } from './cache.mjs';
const port = Number(process.env.PORT ?? 3000);
async function readJson(req) {
let raw = '';
for await (const chunk of req) {
raw += chunk;
if (raw.length > 4096) throw new Error('body too large');
}
return JSON.parse(raw || '{}');
}
createServer(async (req, res) => {
const { pathname } = new URL(req.url, 'http://localhost');
const read = req.method === 'GET' || req.method === 'HEAD';
// Stands in for your real authentication. Never trust a bare header like this.
const user = req.headers['x-demo-user'];
try {
if (read && pathname === '/api/books') {
return send(req, res, 200, { books: catalogue.books }, {
policy: 'catalogue',
lastModified: catalogue.updatedAt,
});
}
if (pathname.startsWith('/api/me/') && !user) {
return send(req, res, 401, { error: 'sign in first' });
}
if (read && pathname === '/api/me/settings') {
return send(req, res, 200, { user, language: 'en', textSize: 'medium' }, { policy: 'settings' });
}
if (read && pathname === '/api/me/loans') {
return send(req, res, 200, { user, loans: loansFor(user) }, { policy: 'personal' });
}
if (req.method === 'POST' && pathname === '/api/me/loans') {
const { bookId } = await readJson(req);
const book = catalogue.books.find((b) => b.id === bookId);
if (!book?.available) return send(req, res, 409, { error: 'book not available' });
book.available = false;
catalogue.updatedAt = new Date();
loansFor(user).push({ bookId, title: book.title });
return send(req, res, 201, { bookId, borrowedBy: user });
}
send(req, res, 404, { error: 'not found' });
} catch {
send(req, res, 400, { error: 'bad request' });
}
}).listen(port, '127.0.0.1', () => console.log(`library API on http://127.0.0.1:${port}`));
JSStart it in your second terminal, from the same folder, and leave it running. --watch restarts the server whenever you save server.mjs or a file it imports, so you will not need to restart it by hand. A restart also resets the in-memory loans:
node --watch server.mjsIt prints library API on http://127.0.0.1:3000. Back in the first terminal, look at the catalogue's headers. -D - prints the response headers and -o /dev/null throws the body away:
curl -s -D - -o /dev/null http://127.0.0.1:3000/api/books
curl -s -o /dev/null -w 'catalogue: %{http_code}, %{size_download} bytes\n' http://127.0.0.1:3000/api/booksCheck it worked
The headers show HTTP/1.1 200 OK, content-type, content-length, Date, Connection and Keep-Alive, and no Cache-Control. The second line reads catalogue: 200, 21431 bytes, or close to it. With no instructions, a cache is allowed to pick its own freshness time for a response like this (RFC 9111 calls it heuristic freshness), which is why every response should say what it wants.
Step 2 · Give each kind of response a Cache-Control policy
Decide the policy per kind of response, not per route, so the choices live in one place. Four directives cover most APIs:
public, max-age=60: any cache, shared or private, may keep it for 60 seconds and reuse it without asking.private: only the reader's own browser or app may keep it, never a CDN or proxy shared between people.no-cache: a cache may keep a copy but must check with your server before every reuse. It does not mean "do not cache".no-store: no cache may write it down at all, not even to disk on the reader's phone.
Create policies.mjs first, so it exists before the new cache.mjs imports it:
cat > policies.mjs <<'JS'
// One line per kind of response. Routes pick one by name.
export const POLICIES = {
// The same for everyone, and fine to be a minute old.
catalogue: 'public, max-age=60',
// One reader's preferences: their own device may keep a copy, but must check it first.
settings: 'private, no-cache',
// Personal data: never written to any cache.
personal: 'no-store',
// Errors, writes and anything without a policy.
never: 'no-store',
};
JSNow rewrite cache.mjs to send the policy. Only a 200 uses the route's policy. Errors and 201 responses always get no-store, so a 401 or a 500 can never be reused for a minute by mistake:
cat > cache.mjs <<'JS'
import { POLICIES } from './policies.mjs';
export function send(req, res, status, payload, { policy = 'never' } = {}) {
const body = Buffer.from(JSON.stringify(payload));
res.writeHead(status, {
'cache-control': POLICIES[status === 200 ? policy : 'never'],
'content-type': 'application/json; charset=utf-8',
'content-length': body.length,
});
res.end(req.method === 'HEAD' ? undefined : body);
}
JSThe server restarts on its own. Ask for each endpoint as Amina and print its Cache-Control, then ask for the loans without signing in:
for path in /api/books /api/me/settings /api/me/loans; do
printf '%s ' "$path"
curl -s -D - -o /dev/null -H 'X-Demo-User: amina' "http://127.0.0.1:3000$path" | tr -d '\r' | grep -i '^cache-control'
done
curl -s -D - -o /dev/null http://127.0.0.1:3000/api/me/loans | tr -d '\r' | grep -i -e '^HTTP' -e '^cache-control'Check it worked
The catalogue shows cache-control: public, max-age=60, settings private, no-cache, and loans no-store. The last command, with no X-Demo-User header, shows HTTP/1.1 401 Unauthorized with cache-control: no-store. If a line shows no cache-control, the restart has not finished: run the command again.
Step 3 · Add a strong ETag and Last-Modified
A validator lets a client keep a copy and still get the latest data. The client sends back what it was given, and your server answers 304 Not Modified with no body if nothing changed:
ETagis an opaque label for this exact representation. Built from a SHA-256 hash of the body bytes, it is a strong validator: two bodies share an ETag only if they are byte for byte the same. The client returns it inIf-None-Match.Last-Modifiedis the time of the last change, to the second. The client returns it inIf-Modified-Since. It is weaker: two changes within one second look the same. When a request carries both headers, the server must useIf-None-Matchand ignore the date.
Rewrite cache.mjs. Validators go only on cacheable 200 answers to GET and HEAD, and the 304 repeats Cache-Control, ETag and Last-Modified so the cache can refresh its copy's instructions:
cat > cache.mjs <<'JS'
import { createHash } from 'node:crypto';
import { POLICIES } from './policies.mjs';
function etagFor(body) {
return `"${createHash('sha256').update(body).digest('base64url').slice(0, 22)}"`;
}
function notModified(req, etag, lastModified) {
const ifNoneMatch = req.headers['if-none-match'];
if (ifNoneMatch) {
// Takes precedence over If-Modified-Since. W/ marks a weak tag, compared loosely here.
if (ifNoneMatch.trim() === '*') return true;
return ifNoneMatch.split(',').some((tag) => tag.trim().replace(/^W\//, '') === etag);
}
const since = Date.parse(req.headers['if-modified-since'] ?? '');
if (!lastModified || Number.isNaN(since)) return false;
// HTTP dates have whole seconds, so drop the milliseconds before comparing.
return Math.floor(lastModified.getTime() / 1000) * 1000 <= since;
}
export function send(req, res, status, payload, { policy = 'never', lastModified } = {}) {
const body = Buffer.from(JSON.stringify(payload));
const cacheControl = POLICIES[status === 200 ? policy : 'never'];
const headers = { 'cache-control': cacheControl };
const read = req.method === 'GET' || req.method === 'HEAD';
if (status === 200 && read && !cacheControl.includes('no-store')) {
headers.etag = etagFor(body);
if (lastModified) headers['last-modified'] = lastModified.toUTCString();
if (notModified(req, headers.etag, lastModified)) {
res.writeHead(304, headers);
return res.end();
}
}
headers['content-type'] = 'application/json; charset=utf-8';
headers['content-length'] = body.length;
res.writeHead(status, headers);
res.end(req.method === 'HEAD' ? undefined : body);
}
JSSave the catalogue's ETag in a shell variable, then send it back the way a browser or app would:
ETAG=$(curl -s -D - -o /dev/null http://127.0.0.1:3000/api/books | tr -d '\r' | awk 'tolower($1) == "etag:" { print $2 }')
echo "ETag: $ETAG"
curl -s -o /dev/null -w 'no validator: %{http_code}, %{size_download} bytes\n' http://127.0.0.1:3000/api/books
curl -s -o /dev/null -w 'If-None-Match: %{http_code}, %{size_download} bytes\n' -H "If-None-Match: $ETAG" http://127.0.0.1:3000/api/books
curl -s -o /dev/null -w 'If-Modified-Since: %{http_code}\n' -H 'If-Modified-Since: Mon, 02 Nov 2026 09:30:00 GMT' http://127.0.0.1:3000/api/booksCheck it worked
The output is something like this, with a different ETag:
ETag: "q3V1mK0sYc8rT2bWfE9xLh"
no validator: 200, 21431 bytes
If-None-Match: 304, 0 bytes
If-Modified-Since: 304The revalidated request moved no body at all. The headers still travel, so a 304 costs a few hundred bytes, not zero. GET /api/me/settings with X-Demo-User: amina now has an ETag too, while /api/me/loans has none, because nothing may store it.
Step 4 · Watch a write change the validators
Caching is only safe if a change to the data changes the validators. Borrow book 1 as Amina. The POST answer is 201 with no-store: a response to a write is a one-off receipt, and the catalogue it changed is the thing to refetch:
curl -s -D - -X POST -H 'X-Demo-User: amina' -H 'Content-Type: application/json' -d '{"bookId":1}' http://127.0.0.1:3000/api/me/loans | tr -d '\r' | grep -i -e '^HTTP' -e '^cache-control' -e 'bookId'Now send the old ETag and the old date again:
curl -s -o /dev/null -w 'old ETag: %{http_code}, %{size_download} bytes\n' -H "If-None-Match: $ETAG" http://127.0.0.1:3000/api/books
curl -s -o /dev/null -w 'old date: %{http_code}\n' -H 'If-Modified-Since: Mon, 02 Nov 2026 09:30:00 GMT' http://127.0.0.1:3000/api/books
curl -s -D - -o /dev/null http://127.0.0.1:3000/api/books | tr -d '\r' | grep -i -e '^etag' -e '^last-modified'Check it worked
The POST shows HTTP/1.1 201 Created, cache-control: no-store and {"bookId":1,"borrowedBy":"amina"}. Both conditional requests now answer 200 with the full body, and the last command shows a new ETag and today's date in last-modified.
Notice what max-age=60 still allows: a client that fetched the catalogue a few seconds before the loan may show book 1 as available for up to a minute without asking. That is the trade you make for speed, so a write must never trust cached data. Here the POST handler checks available itself and answers 409 if the book has gone.
Step 5 · Tell a CDN how long to keep the catalogue
A CDN is a shared cache. It can hold the catalogue for every reader in a region, so your server answers it once instead of once per reader. Two more directives control it:
s-maxage=300applies only to shared caches and replacesmax-agethere. The CDN keeps the catalogue for five minutes; browsers and apps still use 60 seconds.stale-while-revalidate=30lets a cache whose copy has just expired serve it for up to 30 more seconds while it fetches a fresh one in the background, so no reader waits for the refresh.
Rewrite policies.mjs with the longer catalogue line. The other lines do not change:
cat > policies.mjs <<'JS'
// One line per kind of response. Routes pick one by name.
export const POLICIES = {
// The same for everyone. Browsers keep it 1 minute, CDNs 5 minutes,
// and either may serve it 30 seconds past that while it refetches.
catalogue: 'public, max-age=60, s-maxage=300, stale-while-revalidate=30',
// One reader's preferences: their own device may keep a copy, but must check it first.
settings: 'private, no-cache',
// Personal data: never written to any cache.
personal: 'no-store',
// Errors, writes and anything without a policy.
never: 'no-store',
};
JScurl -s -D - -o /dev/null http://127.0.0.1:3000/api/books | tr -d '\r' | grep -i '^cache-control'Check it worked
The line reads cache-control: public, max-age=60, s-maxage=300, stale-while-revalidate=30. Add up the worst case before you choose numbers: after a loan, a reader behind the CDN may see the old catalogue for up to 330 seconds plus their own 60. If that is too long, purge the CDN's copy when the data changes, using your CDN's purge API, or shorten s-maxage. CDNs differ in which directives they honour, so check yours before you rely on stale-while-revalidate.
Step 6 · Compress large responses and send Vary
A 21 KB JSON list of repeated keys compresses very well. When you compress based on the request's Accept-Encoding header, the same URL now has two different bodies, and a shared cache must not hand the gzip one to a client that cannot read it. Vary: Accept-Encoding tells every cache to keep one copy per value of that header.
Each representation also needs its own strong ETag, because the bytes differ. The new cache.mjs hashes the JSON once and adds -gzip to the tag for the compressed form. It compresses only bodies of 1 KB or more, and only after the 304 check, so a revalidation costs no compression work:
cat > cache.mjs <<'JS'
import { createHash } from 'node:crypto';
import { gzipSync } from 'node:zlib';
import { POLICIES } from './policies.mjs';
function etagFor(body, suffix) {
return `"${createHash('sha256').update(body).digest('base64url').slice(0, 22)}${suffix}"`;
}
function notModified(req, etag, lastModified) {
const ifNoneMatch = req.headers['if-none-match'];
if (ifNoneMatch) {
if (ifNoneMatch.trim() === '*') return true;
return ifNoneMatch.split(',').some((tag) => tag.trim().replace(/^W\//, '') === etag);
}
const since = Date.parse(req.headers['if-modified-since'] ?? '');
if (!lastModified || Number.isNaN(since)) return false;
return Math.floor(lastModified.getTime() / 1000) * 1000 <= since;
}
export function send(req, res, status, payload, { policy = 'never', lastModified } = {}) {
let body = Buffer.from(JSON.stringify(payload));
const cacheControl = POLICIES[status === 200 ? policy : 'never'];
const headers = { 'cache-control': cacheControl, vary: 'Accept-Encoding' };
const read = req.method === 'GET' || req.method === 'HEAD';
// A simple check. Middleware in a framework also honours q-values such as gzip;q=0.
const gzip = body.length >= 1024 && /\bgzip\b/i.test(req.headers['accept-encoding'] ?? '');
if (status === 200 && read && !cacheControl.includes('no-store')) {
headers.etag = etagFor(body, gzip ? '-gzip' : '');
if (lastModified) headers['last-modified'] = lastModified.toUTCString();
if (notModified(req, headers.etag, lastModified)) {
res.writeHead(304, headers);
return res.end();
}
}
if (gzip) {
body = gzipSync(body);
headers['content-encoding'] = 'gzip';
}
headers['content-type'] = 'application/json; charset=utf-8';
headers['content-length'] = body.length;
res.writeHead(status, headers);
res.end(req.method === 'HEAD' ? undefined : body);
}
JSLook at the gzip response's headers, then measure the three ways a client can get the catalogue. Without --compressed, curl saves the bytes exactly as they arrived, so size_download is what crossed the network:
curl -s -D - -o /dev/null -H 'Accept-Encoding: gzip' http://127.0.0.1:3000/api/books | tr -d '\r' | grep -i -e '^content-encoding' -e '^vary' -e '^etag'
GZ_ETAG=$(curl -s -D - -o /dev/null -H 'Accept-Encoding: gzip' http://127.0.0.1:3000/api/books | tr -d '\r' | awk 'tolower($1) == "etag:" { print $2 }')
curl -s -o /dev/null -w 'plain: %{size_download} bytes\n' http://127.0.0.1:3000/api/books
curl -s -o /dev/null -w 'gzip: %{size_download} bytes\n' -H 'Accept-Encoding: gzip' http://127.0.0.1:3000/api/books
curl -s -o /dev/null -w 'revalidated: %{size_download} bytes, %{http_code}\n' -H 'Accept-Encoding: gzip' -H "If-None-Match: $GZ_ETAG" http://127.0.0.1:3000/api/booksCheck it worked
The headers include content-encoding: gzip, vary: Accept-Encoding and an ETag ending in -gzip". The sizes are something like plain: 21431 bytes, gzip: 1280 bytes and revalidated: 0 bytes, 304. Sending the gzip ETag without Accept-Encoding: gzip gets a full 200, because that client holds a different representation.
Use Vary for any request header that changes the body. An API that returns English, French, Swahili or Hausa text from one URL based on Accept-Language must send Vary: Accept-Language, or a CDN in Lagos may serve one reader's language to the next. Avoid Vary: Cookie or Vary: User-Agent on public responses: they split the cache into near-unique copies. Personal responses should be private or no-store instead.
Step 7 · Write the policy down and check it
You now have one decision per kind of response. Write it down where your team will see it, in the API's README or design notes:
GET /api/books:public, max-age=60, s-maxage=300, stale-while-revalidate=30, with ETag and Last-Modified. The same for everyone, and a few minutes old is acceptable.GET /api/me/settings:private, no-cache, with an ETag. One reader's data, small, and it must be current.GET /api/me/loans:no-store, no validators. Personal data.POST /api/me/loans:no-store. A write; clients refetch what it changed.- Any
4xxor5xx:no-store. An error must not outlive its cause.
Some responses must never be stored by any cache, whatever their URL: anything that sets a cookie or returns a token, one-time codes, payment and account details, and anything that depends on who is asking unless it is marked private. When in doubt, use no-store and relax it later with evidence.
A table drifts unless something checks it. Create check-policy.mjs, which calls every endpoint, compares the headers to the policy and confirms that each cacheable response revalidates to 304:
cat > check-policy.mjs <<'JS'
const base = process.env.API_URL ?? 'http://127.0.0.1:3000';
const amina = { 'x-demo-user': 'amina' };
const rules = [
{ path: '/api/books', cacheControl: 'public, max-age=60, s-maxage=300, stale-while-revalidate=30', validators: true },
{ path: '/api/me/settings', headers: amina, cacheControl: 'private, no-cache', validators: true },
{ path: '/api/me/loans', headers: amina, cacheControl: 'no-store' },
{ path: '/api/me/loans', status: 401, cacheControl: 'no-store' },
{ path: '/api/no-such-thing', status: 404, cacheControl: 'no-store' },
];
let failures = 0;
for (const rule of rules) {
const res = await fetch(base + rule.path, { headers: rule.headers });
await res.arrayBuffer();
const cacheControl = res.headers.get('cache-control');
const etag = res.headers.get('etag');
const problems = [];
if (res.status !== (rule.status ?? 200)) problems.push(`status ${res.status}`);
if (cacheControl !== rule.cacheControl) problems.push(`cache-control "${cacheControl}"`);
if (rule.validators && !etag) problems.push('no ETag');
if (!rule.validators && etag) problems.push('ETag on a response nothing may store');
if (rule.validators && etag) {
const again = await fetch(base + rule.path, { headers: { ...rule.headers, 'if-none-match': etag } });
if (again.status !== 304) problems.push(`revalidation gave ${again.status}`);
}
if (problems.length) failures += 1;
const mark = problems.length ? 'FAIL' : 'ok';
console.log(`${mark.padEnd(5)}${String(res.status).padEnd(5)}${rule.path.padEnd(20)}${cacheControl}`);
for (const problem of problems) console.log(` ${problem}`);
}
console.log(failures ? `${failures} endpoint(s) break the policy` : 'policy OK');
process.exitCode = failures ? 1 : 0;
JS
node check-policy.mjsCheck it worked
Five lines start with ok, one per rule, and the last line reads policy OK. To see a failure, change personal: 'no-store' to personal: 'private, max-age=60' in policies.mjs, wait a second for the restart and run node check-policy.mjs again: the /api/me/loans line shows FAIL with the wrong header, and the script exits with code 1. Put the line back afterwards. Run the script in CI against a test deployment, so a change to a header is a reviewed decision.
Step 8 · Clean up
Stop the server with Ctrl+C in the second terminal. Then delete the demo folder:
cd ~
rm -rf ~/api-cache-demoCheck it worked
ls ~/api-cache-demo reports that the folder does not exist, and curl http://127.0.0.1:3000/api/books fails to connect.
Next steps
- Browsers send their own headers to cross-origin APIs, and preflight answers can be cached too: configure CORS for an API.
- See the same ideas inside a framework, with tags and revalidation: cache library pages with Next.js cache components.
- Practise reading headers and timing requests: test an API with curl.
- Move the policy into an Express app: build a REST API with Express 5.
Part of these paths
Related tutorials
- Configure CORS for an API without opening it to everyoneYou will reproduce a browser CORS error with a page and an API on different ports, then fix it in Express 5.3 with an origin allowlist, preflight handling, credentials, Vary and preflight caching, and prove each header with curl and Playwright.
- Cache library pages with Next.js 16 Cache Components and refresh them on changeYou will cache the library catalogue with the "use cache" directive, cacheLife and cacheTag, refresh it with updateTag after every edit or loan and with revalidateTag from outside the app, and end with a fast catalogue that never serves a lent book as available.
- How to Test and Debug an API with curlYou will write a small practice API, then call it with curl 8 to read responses and headers, send JSON, send an authorization header without putting the secret on the command line, follow redirects, measure timing, set timeouts and retries, and read curl's verbose output when a request goes wrong.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials