Skip to the code

Network first, with a timeout

MediumCaching

The tea shop's pages should be as fresh as the server can make them, but a visitor on a train with one bar of signal shouldn't stare at a blank screen for 30 seconds when the cache has yesterday's copy. Write networkFirst(event, options), which the service worker's fetch handler calls for page requests. It must call event.respondWith() before it returns.

Fetch event.request at once. If the network's response arrives within options.timeout milliseconds (3000 when it isn't given), answer with it, whatever its status. If the time runs out first, look in the options.cacheName cache ("tea-shop-pages" when it isn't given) and answer with its copy; if it has none, keep waiting for the network. If the fetch fails (it rejects, as it does offline), answer from the cache at once, without waiting for the timeout; with nothing cached either, the answer fails with the fetch's error. Once the network has answered or failed, the timer has no job left: clear it.

Whenever the network's response arrives, even after the cache has answered, store a copy in the cache if the response is ok, so the next visit gets it. The worker may be stopped once the page has its answer, so keep it alive with event.waitUntil() until the copy is stored. waitUntil() only works while the event is being dispatched, or while an earlier promise it was given is still pending, and by the time a slow network answers, the cached answer may be long done: call waitUntil() up front.

This is how Workbox's NetworkFirst strategy works with its networkTimeoutSeconds option. The tests run on a fake clock (useFakeTimers()), with a network (useFetch()) whose answers can take time on that clock.

self.addEventListener("fetch", (event) => {
  if (event.request.mode === "navigate") networkFirst(event, { timeout: 3000 });
});
// A good connection: the page comes from the network, and a copy goes in "tea-shop-pages".
// The network takes 8 s: at 3 s, the copy from the last visit answers; at 8 s, the new page replaces it in the cache.
// Offline: the copy answers at once.

What the tests check

  1. answers from the network when it's quick, and keeps a copy
    const clock = useFakeTimers();
    const cacheStorage = useCaches();
    useFetch(() => ({ body: "<h1>Today's teas</h1>", headers: { "content-type": "text/html" }, delay: 200 }));
    const event = fetchEvent("/menu");
    networkFirst(event);
    await clock.tickAsync(200);
    expect(await (await event.response()).text()).toBe("<h1>Today's teas</h1>");
    await event.settled();
    expect(cacheStorage.contents()).toEqual({ "tea-shop-pages": ["https://example.test/menu"] });
    expect(await (await caches.match("/menu")).text()).toBe("<h1>Today's teas</h1>");
    
  2. waits for the network until the timeout, even with a copy in the cache
    const clock = useFakeTimers();
    useCaches();
    await (await caches.open("tea-shop-pages")).put("/menu", new Response("yesterday's menu"));
    useFetch(() => ({ body: "today's menu", delay: 2900 }));
    const event = fetchEvent("/menu");
    networkFirst(event);
    await clock.tickAsync(2900);
    expect(await (await event.response()).text()).toBe("today's menu");
    
  3. after the timeout, answers with the cached copy, then stores the network's response when it comes
    const clock = useFakeTimers();
    useCaches();
    await (await caches.open("tea-shop-pages")).put("/menu", new Response("yesterday's menu"));
    useFetch(() => ({ body: "today's menu", delay: 8000 }));
    const event = fetchEvent("/menu");
    networkFirst(event);
    let answer = "no answer yet";
    event.response().then((response) => (answer = response), (error) => (answer = error));
    await clock.tickAsync(2999);
    expect(answer).toBe("no answer yet");
    await clock.tickAsync(1);
    for (let turn = 0; turn < 20 && answer === "no answer yet"; turn++) await flush();
    expect(await answer.text()).toBe("yesterday's menu");
    await clock.tickAsync(5000);
    await event.settled();
    expect(await (await caches.match("/menu")).text()).toBe("today's menu");
    
  4. a network error answers from the cache at once, without waiting for the timeout
    useFakeTimers();
    useCaches();
    await (await caches.open("tea-shop-pages")).put("/menu", new Response("yesterday's menu"));
    useFetch(() => {
      throw new TypeError("Failed to fetch");
    });
    const event = fetchEvent("/menu");
    networkFirst(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("yesterday's menu");
    
  5. with nothing cached when the time runs out, keeps waiting for the network
    const clock = useFakeTimers();
    useCaches();
    useFetch(() => ({ body: "today's menu", delay: 5000 }));
    const event = fetchEvent("/menu");
    networkFirst(event);
    let answer = "no answer yet";
    event.response().then((response) => (answer = response), (error) => (answer = error));
    await clock.tickAsync(3000);
    for (let turn = 0; turn < 5; turn++) await flush();
    expect(answer).toBe("no answer yet");
    await clock.tickAsync(2000);
    expect(await (await event.response()).text()).toBe("today's menu");
    await event.settled();
    expect(await (await caches.match("/menu")).text()).toBe("today's menu");
    
  6. with nothing cached, a network error fails the answer
    useFakeTimers();
    useCaches();
    useFetch(() => {
      throw new TypeError("Failed to fetch");
    });
    const event = fetchEvent("/menu");
    networkFirst(event);
    await expect(event.response()).rejects.toThrow("Failed to fetch");
    
  7. answers with a response that isn't ok, and doesn't store it
    const clock = useFakeTimers();
    useCaches();
    await (await caches.open("tea-shop-pages")).put("/menu", new Response("yesterday's menu"));
    useFetch(() => ({ status: 500, body: "The kettle is broken", delay: 100 }));
    const event = fetchEvent("/menu");
    networkFirst(event);
    await clock.tickAsync(100);
    expect((await event.response()).status).toBe(500);
    await event.settled();
    expect(await (await caches.match("/menu")).text()).toBe("yesterday's menu");
    
  8. takes another timeout and cache name
    const clock = useFakeTimers();
    const cacheStorage = useCaches();
    await (await caches.open("tea-shop-pages-v2")).put("/reviews", new Response("12 reviews"));
    useFetch(() => ({ body: "13 reviews", delay: 2000 }));
    const event = fetchEvent("/reviews");
    networkFirst(event, { timeout: 500, cacheName: "tea-shop-pages-v2" });
    let answer = "no answer yet";
    event.response().then((response) => (answer = response), (error) => (answer = error));
    await clock.tickAsync(500);
    for (let turn = 0; turn < 20 && answer === "no answer yet"; turn++) await flush();
    expect(await answer.text()).toBe("12 reviews");
    await clock.tickAsync(1500);
    await event.settled();
    expect(cacheStorage.contents()).toEqual({ "tea-shop-pages-v2": ["https://example.test/reviews"] });
    expect(await (await caches.match("/reviews")).text()).toBe("13 reviews");
    
  9. clears its timer once the network has answered
    const clock = useFakeTimers();
    useCaches();
    useFetch(() => ({ body: "today's menu", delay: 100 }));
    const event = fetchEvent("/menu");
    networkFirst(event);
    await clock.tickAsync(100);
    await event.response();
    await event.settled();
    expect(clock.pending()).toBe(0);
    

Learn more

solution.jsSaved in this browser

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).