Francisco Brusa

The Service Workers Cache API and the Fetch Event

A Service Worker is a script that runs in a different environment than the browser, running only once per domain instead of once per tab. It does not executes again if the page refreshes and it's not loaded with a script tag like this: <script src="">; instead it's loaded with some javascript code like this: navigator.serviceWorker.register("/serviceWorker.js")

One of the most powerful features of Service Workers is the Cache API in conjunction with the Fetch Event. With them you have the ability to intercept any outbound network request and modify, store, and retrieve from cache the response.

By any outbound network request I mean literally any one of them. It doesn't matter if the browser tries to fetch a resource from another domain, or if the browser is offline. It doesn't matter either if you're trying to fetch via GET or POST and weather you're receiving a script, an image or an html document.

When intercepting a request, you're allowed to modify it's response. You can choose to actually make a real request and then store the response in cache, or you can retrieve a previous version of that request from cache. It's also possible (although maybe not recommended) to modify the contents, headers or status code of the response.

The Cache API (WindowOrWorkerGlobalScope.caches)

This caching mechanism works as a collection of request/response keys.

Most examples of using the WindowOrWorkerGlobalScope.caches out there explain how to cache and then serve assets from Service Workers.

Here's a thorough one example from github (showing only relevant parts). Don't worry if it feels a little overwhelming right now, later on we will go back to some more familiar code and explain step by step how everything works.

1function returnNoNetwork() {
2 return"core-v" + VERSION).then((cache) => {
3 return cache.match(HOME + "post");
4 });
7self.addEventListener("fetch", function (e) {
8 let fonts = new RegExp("^assetsPublic/fonts/", "i");
9 let images = new RegExp("^assetsPublic/img/", "i");
10 let viewJs = new RegExp("^assetsPublic/view/", "i");
11 let core = new RegExp("^assetsPublic/", "i");
12 let linkExterno = new RegExp("^https*://", "i");
14 if (linkExterno.test(url)) {
15 e.respondWith(fetch(e.request));
16 } else if (core.test(url)) {
17 let cacheName = viewJs.test(url)
18 ? "viewUserJs"
19 : fonts.test(url)
20 ? "fonts"
21 : images.test(url)
22 ? "images"
23 : "core";
24 e.respondWith(
25 caches
26 .open(cacheName + "-v" + VERSION)
27 .then((cache) => {
28 return cache.match(url).then((response) => {
29 return (
30 response ||
31 fetch(e.request)
32 .then((networkResponse) => {
33 if (
34 networkResponse &&
35 networkResponse.status === 200 &&
36 networkResponse.type === "basic"
37 ) {
38 cache.put(url, networkResponse.clone());
39 return networkResponse;
40 }
41 return returnNoNetwork();
42 })
43 .catch(() => {
44 return returnNoNetwork();
45 })
46 );
47 });
48 })
49 );
50 }

You will notice that most examples focus on how to use the Cache API ( in Service Workers, but you can use it in a good old script tag just as well.

To understand the Cache API, we will first start by some example code that can work both in the browser and inside a service worker, using the fetch function.

But first, let's talk about the Request Class. The Request class works very well with the fetch function, because they have identical signatures.

new Request("/test", options);
fetch("/test", options);

The fetch function can be called using a Request object.

const request = new Request("/test", options);

Additionally, we can add entries to the cache using request and response objects...

fetch(request).then((response) => {
cache.put(request, response);

We can later retrieve this entry from the cache by matching our cache entry agains a similar Request object.

cache.match(request).then((response) => {
// ...

Using caches we don't have to worry about correctly serializing the request object before caching it.

Having seen all these examples, you'll notice by now that in order to take advantage of the very powerfull Cache API, you don't need to use a Service Worker. It can be used alongside the fetch function, which is supported in the Browser Environment.

Here's a functional replacement to the fetch function that works both inside the browser and in a Service Worker. It will return results in what --in Workbox parlage-- it's called a "Cache First" strategy.

1// Use this function just like fetch()
2// it will return results from cache if they're available
3const fetchUsingCacheFirstStrategy = async (...opts) => {
4 // the request constructor has exactly the same
5 // signature as the fetch function
6 const request = new Request(...opts);
8 // attempt at retrieving response from cache
9 const cache = await;
10 const cachedResponse = await cache.match(request);
12 if (cachedResponse) {
13 console.log(`retrieving response from cache`);
14 return cachedResponse;
15 }
17 // no response stored in cache.
18 // perform the request
19 console.log(`starting request`);
20 const response = await fetch(request);
22 if (response.ok) {
23 console.log(`saving response to cache`);
24 cache.put(request, response);
25 }
27 return response;

Here's some example usage:

1const CACHE_NAME = "test";
3// call first time
5// starting request
6// saving response to cache
8// call a second time
10// retrieving response from cache

Of course this example does not consider cache invalidation, so it's not a production-ready code.

What's powerful about Service Workers is that they can listen to a FetchEvent type of event via self.addEventListener("fetch"). Unlike the fetchUsingCacheFirstStrategy function stated above, with this event you can not only use cache strategies for XHR requests made via JavaScript; it's also possible to use cache strategies for requests that the browser emits when fetching scripts, stylesheets, images, or any other kind of request.

The fetch event triggers on any request made by the browser, not just those made using fetch(). This event will fire when calling XMLHttpRequest and with requests triggered by some HTML tags such as img, link and svg.

When listening to the fetch event, the actual request is intercepted, meaning no request is made until we explicitly do so. This means we can prevent the request to get executed if we want to.

This simple code adds a header to any outbound request made by our web app.

1self.addEventListener("fetch", (e) => {
2 // extend original request to add new header
3 const request = new Request(e.request, {
4 headers: new Headers({
5 "X-My-Custom-Header": "Zeke are cool",
6 }),
7 });
9 e.respondWith(fetch(request));

Of course we can use this in convination with the cache API to return responses from cache using a CacheFirst strategy, as descrived above.

In this example, we return all images using a Cache first strategy

1const CACHE_NAME = process.env.GIT_SHA;
3self.addEventListener("fetch", async (event) => {
4 if (isRequestingImage(event.request)) {
5 return fetchUsingCacheFirstStrategy(event.request);
6 }
9function isRequestingImage(request) {
10 return /image\/[^,]+$/i.test(
11 request.headers.get("Accept")
12 );


It's possible to use the Cache API both in a browser and in a service worker, but only in a service worker you can take advantage of this API to determine how images and other non-XHR requests are handled.

This means it's possible to start using the Cache API only in the browser to handle certain API calls, and integrate it in a service worker only when the need of caching non-API calls (or offering offline support) arises.

The MDM documentation is always a great resource. You can read info about the APIs covered in this article here: FetchEvent API (for Workers), Fetch API and Cache API.