Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 37 ยท Service Workers

The Fetch Event and respondWith

Master the service worker fetch event: inspect requests, use respondWith, route by URL and method, build an offline fallback page and avoid common response mistakes.

The fetch event is where a service worker earns its keep. Every request made by a controlled page (navigations, scripts, images, API calls) arrives as a FetchEvent in the worker. If you do nothing, the browser handles it normally. If you call event.respondWith(...), you decide the response. This lesson shows how to read a request, route it, answer from caches or the network, and build an offline fallback.

Anatomy of a fetch handler

JavaScript
self.addEventListener('fetch', (event) => {
  const request = event.request;
  console.log(request.method, request.url, request.mode, request.destination);
  // do nothing: the browser performs the request normally
});

The event.request is a standard Request. The members you will use most:

  • request.method: GET, POST, ...
  • request.url: the full URL (parse it with new URL(request.url)).
  • request.mode: navigate for page loads, cors, no-cors and same-origin for others.
  • request.destination: what it is for: document, script, style, image, font...
  • request.headers: for example Accept.

Returning from the handler without calling respondWith means "I'm not handling this one". That is the way to opt out: the browser makes the request as if there were no service worker.

respondWith

event.respondWith() takes a Response or a promise for one. It must be called synchronously inside the event handler, before the handler returns; you cannot call it later in a promise callback. After you call it, the browser waits for your promise.

JavaScript
self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request).then((cached) => cached || fetch(event.request))
  );
});

If the promise rejects or resolves to something that is not a Response, the page sees a network error. A valid response is also required to match the request's expectations: for example you cannot answer a cors request with an opaque response from a no-cors fetch in a way that breaks the page (details below).

You can also construct responses yourself:

JavaScript
event.respondWith(
  new Response(JSON.stringify({ ok: true }), {
    status: 200,
    headers: { 'Content-Type': 'application/json' },
  })
);

Routing by request

Real workers branch on the request. A tidy pattern is a small router:

JavaScript
self.addEventListener('fetch', (event) => {
  const { request } = event;
  if (request.method !== 'GET') return;                 // never cache POST etc.

  const url = new URL(request.url);
  if (url.origin !== self.location.origin) return;      // leave third parties alone

  if (request.mode === 'navigate') {
    event.respondWith(networkFirstWithOfflinePage(request));
  } else if (url.pathname.startsWith('/api/')) {
    event.respondWith(networkFirst(request));
  } else if (request.destination === 'image') {
    event.respondWith(cacheFirst(request));
  }
  // anything else: not handled, the browser fetches it normally
});

Each helper is a function that returns a promise of a Response; chapter 4 implements them as full strategies. The router itself is the topic of the next stand-in.

A runnable request router

This stand-in routes fake requests the way the handler above does. It uses real Request and Response objects so the logic is faithful, but no service worker is involved.

JS Stand-in: a request router

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The offline fallback page

When the network is gone and nothing is cached, the user would see the browser's error page. A PWA shows its own friendly page instead. Cache /offline.html in install, then fall back to it for navigations that fail:

JavaScript
async function networkFirstWithOfflinePage(request) {
  try {
    return await fetch(request);
  } catch (error) {
    const cached = await caches.match(request);
    return cached || caches.match('/offline.html');
  }
}

Keep offline.html self-contained: inline its CSS and use only assets that are also cached, otherwise the offline page itself looks broken. Offer a "Try again" button that calls location.reload().

You can design the page right here. It is an ordinary HTML page:

Design an offline page

Handling cross-origin requests

Requests to other origins (a CDN, an analytics service, fonts) can be handled, but with limits. If a no-cors request returns an opaque response (response.type === 'opaque', status 0), you cannot read it, and you cannot know if it succeeded. It can still be cached and returned to the page, but opaque responses can take large amounts of cache quota (browsers pad their size). Prefer CORS-enabled resources (crossorigin attribute on tags plus proper headers) when you plan to cache third-party assets, or leave third parties alone.

Cloning responses

A Response body can be read only once. To both cache a response and return it, clone it first:

JavaScript
const response = await fetch(request);
const copy = response.clone();
caches.open('v1').then((cache) => cache.put(request, copy));
return response;

Forgetting clone() leads to "body already used" errors. Check this in the next TryIt.

JS Why you need response.clone()

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Other things worth knowing

  • Range requests (video seeking) need careful handling if you cache media; a cached full response does not satisfy a Range request unless you slice it.
  • Redirects: responses with redirected: true cannot be used to answer a navigation when the redirect mode is manual; clone them into a new Response if you hit this.
  • event.waitUntil inside fetch lets you finish background work after responding, for example updating a cache in the stale-while-revalidate strategy.
  • Only same-origin, GET requests belong in a typical caching router. Don't cache POST.
  • event.preloadResponse is the navigation preload response when enabled.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens if a fetch handler returns without calling respondWith?

    Not calling respondWith opts out for that request.
  2. 2. When must respondWith be called?

    The browser needs to know you will respond before the handler finishes.
  3. 3. Why call response.clone() before putting a response in the cache?

    One copy goes to the cache, the other is returned to the page.
  4. 4. Which requests have mode 'navigate'?

    Navigation requests load documents and are often handled specially, for offline pages.
  5. 5. What is an opaque response?

    Opaque responses hide their details from scripts and can use large amounts of quota when cached.

Summary

  • The fetch event gives you every request of controlled pages; call respondWith synchronously to answer.
  • Return without it to let the browser handle the request.
  • Route by method, origin, mode and destination; ignore non-GET and third-party requests unless you mean to handle them.
  • Cache an offline page in install and serve it as a navigation fallback.
  • Clone responses before caching and returning them.

Next: Service Worker Updates