The tea shop's reviews and stock levels change during the day, but a copy from a few minutes ago is fine to show at once. Write staleWhileRevalidate(event, options), which the service worker's fetch handler calls for those requests. It must call event.respondWith() before it returns.
Look for the request in the options.cacheName cache ("tea-shop-api" when it isn't given), and start fetching it at the same time, so that on a miss the request is already on its way. If the cache has a copy, answer with it straight away, without waiting for the network. When the network's response arrives, store a copy if it's ok, replacing the old one, so the next request gets it. If the cache has nothing, answer with the network's response, and store it too if it's ok. Make one network request per event, never two.
A refresh that fails, offline or with a response that isn't ok, leaves the cached copy as it was, and doesn't fail anything: the page already has its answer, so every promise you give the event should fulfill. With nothing cached, a failed fetch fails the answer with its error. Keep the worker alive with event.waitUntil() until the refresh is stored, and call it before your first await, since later it only works while an earlier promise is still pending.
This is Workbox's StaleWhileRevalidate strategy. It takes its name from HTTP's stale-while-revalidate directive (RFC 5861), but it has no time window: every request answers from the cache and refreshes it. The JavaScript problem Stale-while-revalidate cache (stale-while-revalidate) builds the idea around a function's results in memory; this one works on requests and Cache Storage, within a service worker event's lifetime.
self.addEventListener("fetch", (event) => {
if (new URL(event.request.url).pathname.startsWith("/api/reviews")) staleWhileRevalidate(event);
});
// First visit: nothing stored, so the reviews come from the network, and a copy is stored.
// Every visit after: the stored reviews show at once, and the network's newer ones replace them for next time.
useFakeTimers();
useCaches();
await (await caches.open("tea-shop-api")).put("/api/reviews", new Response("12 reviews"));
useFetch(() => ({ body: "13 reviews", delay: 5000 }));
const event = fetchEvent("/api/reviews");
staleWhileRevalidate(event);
let answer = "no answer yet";
event.response().then((response) => (answer = response), (error) => (answer = error));
for (let turn = 0; turn < 20 && answer === "no answer yet"; turn++) await flush();
expect(await answer.text()).toBe("12 reviews");
const clock = useFakeTimers();
useCaches();
await (await caches.open("tea-shop-api")).put("/api/reviews", new Response("12 reviews"));
useFetch(() => ({ body: "13 reviews", delay: 1000 }));
const first = fetchEvent("/api/reviews");
staleWhileRevalidate(first);
expect(await (await first.response()).text()).toBe("12 reviews");
await clock.tickAsync(1000);
await first.settled();
const second = fetchEvent("/api/reviews");
staleWhileRevalidate(second);
expect(await (await second.response()).text()).toBe("13 reviews");
useCaches();
await (await caches.open("tea-shop-api")).put("/api/reviews", new Response("12 reviews"));
const network = useFetch(() => ({ body: "13 reviews" }));
const event = fetchEvent("/api/reviews");
staleWhileRevalidate(event);
expect(network.calls.map((call) => call.url)).toEqual(["https://example.test/api/reviews"]);
await event.settled();
useCaches();
const network = useFetch(() => ({ body: "3 oolongs left" }));
const event = fetchEvent("/api/stock/oolong");
staleWhileRevalidate(event);
expect(await (await event.response()).text()).toBe("3 oolongs left");
await event.settled();
expect(network.calls).toHaveLength(1);
expect(await (await caches.match("/api/stock/oolong")).text()).toBe("3 oolongs left");
useCaches();
await (await caches.open("tea-shop-api")).put("/api/reviews", new Response("12 reviews"));
useFetch(() => {
throw new TypeError("Failed to fetch");
});
const event = fetchEvent("/api/reviews");
staleWhileRevalidate(event);
expect(await (await event.response()).text()).toBe("12 reviews");
const outcomes = await event.settled();
expect(outcomes.map((outcome) => outcome.status).filter((status) => status !== "fulfilled")).toEqual([]);
expect(await (await caches.match("/api/reviews")).text()).toBe("12 reviews");
useCaches();
await (await caches.open("tea-shop-api")).put("/api/reviews", new Response("12 reviews"));
useFetch(() => ({ status: 503, body: "Back soon" }));
const event = fetchEvent("/api/reviews");
staleWhileRevalidate(event);
expect(await (await event.response()).text()).toBe("12 reviews");
await event.settled();
expect(await (await caches.match("/api/reviews")).text()).toBe("12 reviews");
useCaches();
useFetch(() => {
throw new TypeError("Failed to fetch");
});
const event = fetchEvent("/api/reviews");
staleWhileRevalidate(event);
await expect(event.response()).rejects.toThrow("Failed to fetch");
useCaches();
useFetch(() => ({ status: 404, body: "No such tea" }));
const event = fetchEvent("/api/stock/rooibos");
staleWhileRevalidate(event);
expect((await event.response()).status).toBe(404);
await event.settled();
expect(await caches.match("/api/stock/rooibos")).toBe(undefined);
const clock = useFakeTimers();
const cacheStorage = useCaches();
await (await caches.open("tea-shop-stock-v1")).put("/api/stock/mint", new Response("9 left"));
useFetch(() => ({ body: "8 left", delay: 100 }));
const event = fetchEvent("/api/stock/mint");
staleWhileRevalidate(event, { cacheName: "tea-shop-stock-v1" });
expect(await (await event.response()).text()).toBe("9 left");
await clock.tickAsync(100);
await event.settled();
expect(cacheStorage.contents()).toEqual({ "tea-shop-stock-v1": ["https://example.test/api/stock/mint"] });
expect(await (await caches.match("/api/stock/mint")).text()).toBe("8 left");
Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.
Ctrl + Enter runs the tests (⌘ + Enter on a Mac).
I'm here to help with Stale-while-revalidate in a service worker. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.