Is this cached response fresh?
The browser's HTTP cache holds five of the tea shop's responses. The code checks each one at the same moment with RFC 9111's rules, as a private cache like the browser's does, and logs whether it's fresh, with its freshness lifetime and its age in seconds. What does it log?
// RFC 9111's freshness check, as the browser's own (private) cache makes it. Times are in seconds.
const seconds = (httpDate) => Date.parse(httpDate) / 1000;
function freshness({ headers, received }, now) {
// The freshness lifetime: the first rule that applies.
const maxAge = /(?:^|,)\s*max-age=(\d+)/.exec(headers["cache-control"] ?? "");
let lifetime = 0;
if (maxAge) lifetime = Number(maxAge[1]);
else if (headers.expires) lifetime = Math.max(0, seconds(headers.expires) - seconds(headers.date));
else if (headers["last-modified"]) lifetime = (seconds(headers.date) - seconds(headers["last-modified"])) / 10;
// The age: how old it already was when it arrived, plus the time it has been stored since.
const apparentAge = Math.max(0, received - seconds(headers.date));
const ageWhenReceived = Math.max(apparentAge, Number(headers.age ?? 0));
const age = ageWhenReceived + (now - received);
return { state: lifetime > age ? "fresh" : "stale", lifetime, age };
}
const now = seconds("Tue, 24 Nov 2026 12:00:00 GMT");
const stored = {
// The shop's CDN had kept it for 9 minutes before the browser got it, 2 minutes ago.
"menu.json": {
headers: { "cache-control": "max-age=600", age: "540", date: "Tue, 24 Nov 2026 11:49:00 GMT" },
received: now - 120,
},
"basket.json": {
headers: { "cache-control": "max-age=0", expires: "Wed, 25 Nov 2026 11:00:00 GMT", date: "Tue, 24 Nov 2026 11:00:00 GMT" },
received: now - 3600,
},
"prices.json": {
headers: { expires: "Tue, 24 Nov 2026 12:30:00 GMT", date: "Tue, 24 Nov 2026 11:30:00 GMT" },
received: now - 1800,
},
"logo.svg": {
headers: { "last-modified": "Sat, 14 Nov 2026 09:00:00 GMT", date: "Tue, 24 Nov 2026 09:00:00 GMT" },
received: now - 10800,
},
"about.html": {
headers: { "last-modified": "Tue, 24 Nov 2026 10:50:00 GMT", date: "Tue, 24 Nov 2026 11:50:00 GMT" },
received: now - 600,
},
};
for (const [file, response] of Object.entries(stored)) {
const { state, lifetime, age } = freshness(response, now);
console.log(`${file}: ${state} (lifetime ${lifetime} s, age ${age} s)`);
}
Practice it in the editor, with tests
The answer
Work out every line it logs, in order. Then check.
Checking your sign-in…