Skip to the code

Cache first

The tea shop's hashed files, like /assets/app.3f9a1c.js, never change under the same URL, so a returning visitor shouldn't wait for the network to get them. Write handleFetch(event), the service worker's fetch handler (self.addEventListener("fetch", handleFetch)), with the cache-first strategy.

Handle only GET requests for the shop's own origin, ORIGIN in the starter (in a real service worker, self.location.origin); compare whole origins, not the start of the URL. Leave every other request to the browser by returning without calling event.respondWith(): a POST of an order must reach the server, and a cross-origin font or analytics call isn't the shop's to cache.

For the rest, call event.respondWith() at once with a promise of the answer. Look for the request in every cache, with caches.match(), so files another part of the worker stored (at install, say) count too. If a cache has it, answer with it and don't use the network. If none does, fetch the request and answer with the response, and store a copy in the "tea-shop-runtime" cache, but only when the response is ok (a status from 200 to 299): a 404 or a 500 stored now would be served on every visit. If the fetch fails, the answer fails with its error, as it would without a service worker.

The tests give you a FetchEvent (fetchEvent()), Cache Storage (useCaches()), and fetch (useFetch()) that behave as the Service Workers spec says: respondWith() only works while the event is being dispatched, waitUntil() keeps the worker alive for work that outlasts the answer (and works after an await only while an earlier promise is still pending), and cache.put() reads the response's body, which can only be read once. The interview question Write a cache-first service worker handler (write-a-cache-first-handler) is a simpler version of this, with one cache and every GET.

self.addEventListener("fetch", handleFetch);
// First visit: /assets/app.3f9a1c.js comes from the network, and a copy goes in "tea-shop-runtime".
// Every visit after: it comes from the cache, with no request at all.
// POST /api/orders and https://fonts.example.com/tea-sans.woff2: the browser handles them as usual.

What the tests check

  1. on a miss, answers from the network and keeps a copy in tea-shop-runtime
    const cacheStorage = useCaches();
    const network = useFetch(() => ({ body: "body { margin: 0; }", headers: { "content-type": "text/css" } }));
    const event = fetchEvent("/assets/styles.9b2e07.css");
    handleFetch(event);
    expect(await (await event.response()).text()).toBe("body { margin: 0; }");
    expect(network.calls.map((call) => call.url)).toEqual(["https://example.test/assets/styles.9b2e07.css"]);
    await event.settled();
    expect(cacheStorage.contents()).toEqual({ "tea-shop-runtime": ["https://example.test/assets/styles.9b2e07.css"] });
    
  2. answers from whichever cache has the file, without the network
    useCaches();
    const network = useFetch(() => ({ body: "from the network" }));
    const precache = await caches.open("tea-shop-v2");
    await precache.put("/assets/app.3f9a1c.js", new Response("console.log('Leaf and Kettle')"));
    const event = fetchEvent("/assets/app.3f9a1c.js");
    handleFetch(event);
    expect(await (await event.response()).text()).toBe("console.log('Leaf and Kettle')");
    expect(network.calls).toHaveLength(0);
    
  3. the page and the cache each get the whole body: the response is cloned before it's stored
    useCaches();
    useFetch(() => ({ body: "green, mint, oolong" }));
    const event = fetchEvent("/assets/teas.4c1d.json");
    handleFetch(event);
    expect(await (await event.response()).text()).toBe("green, mint, oolong");
    await event.settled();
    const stored = await (await caches.open("tea-shop-runtime")).match("/assets/teas.4c1d.json");
    expect(await stored.text()).toBe("green, mint, oolong");
    
  4. the second request for a file is answered from the cache
    useCaches();
    const network = useFetch(() => ({ body: "body { margin: 0; }" }));
    const first = fetchEvent("/assets/styles.9b2e07.css");
    handleFetch(first);
    await first.response();
    await first.settled();
    const second = fetchEvent("/assets/styles.9b2e07.css");
    handleFetch(second);
    expect(await (await second.response()).text()).toBe("body { margin: 0; }");
    expect(network.calls).toHaveLength(1);
    
  5. answers with a response that isn't ok, without storing it
    useCaches();
    useFetch((url) => (url.endsWith("rooibos.jpg") ? { status: 404, body: "No such tea" } : { status: 500, body: "Kettle on fire" }));
    const missing = fetchEvent("/assets/rooibos.jpg");
    handleFetch(missing);
    expect((await missing.response()).status).toBe(404);
    await missing.settled();
    const broken = fetchEvent("/assets/app.3f9a1c.js");
    handleFetch(broken);
    expect((await broken.response()).status).toBe(500);
    await broken.settled();
    expect(await caches.match("/assets/rooibos.jpg")).toBe(undefined);
    expect(await caches.match("/assets/app.3f9a1c.js")).toBe(undefined);
    
  6. leaves requests that aren't GET to the browser
    useCaches();
    const network = useFetch(() => ({ status: 201 }));
    const event = fetchEvent("/api/orders", { method: "POST", body: "2 x oolong" });
    handleFetch(event);
    expect(await event.response()).toBe(undefined);
    await event.settled();
    expect(network.calls).toHaveLength(0);
    
  7. leaves requests for any other origin to the browser, even one whose URL starts the same
    useCaches();
    const network = useFetch(() => ({ body: "not the shop's" }));
    for (const url of ["https://fonts.example.com/tea-sans.woff2", "https://example.test.evil.example/assets/app.js", "http://example.test/assets/app.js", "https://example.test:8443/assets/app.js"]) {
      const event = fetchEvent(url);
      handleFetch(event);
      expect(await event.response()).toBe(undefined);
    }
    expect(network.calls).toHaveLength(0);
    
  8. when the network fails and nothing is cached, the answer fails with the network's error
    useCaches();
    useFetch(() => {
      throw new TypeError("Failed to fetch");
    });
    const event = fetchEvent("/assets/app.3f9a1c.js");
    handleFetch(event);
    await expect(event.response()).rejects.toThrow("Failed to fetch");
    

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