Skip to content
AnswerWell geo Documentation

Research · 10 min read · Answerwell

Workbox Service Worker Lifecycle, Routing, and Caching Strategies

How Workbox handles service worker registration, updates, precaching, runtime routes, recipes, and common caching pitfalls on the web.

This page summarises Google Chrome Developers documentation on Workbox: how service workers proxy the network, how Workbox modules handle routing and caching, and how to register and update workers from the page without the subtle lifecycle bugs that appear when using the low-level Service Worker API alone.

Service workers and Workbox: what they are

Section titled “Service workers and Workbox: what they are”

A service worker sits between the browser and your server. It can improve reliability (offline use) and performance by intercepting fetches and using the programmable Cache API, which is wholly separate from the HTTP cache. Browsers that do not support service workers keep normal page behavior—a progressive enhancement model described in the service worker overview.

Workbox is Google’s recommended library for that work. Chrome’s Lighthouse PWA guidance states:

Success: Workbox is the recommended approach for adding service workers to websites because it automates a lot of the boilerplate, makes it easier to follow best practices, and prevents subtle bugs that are common when using the low-level ServiceWorker API directly.

— Google Chrome Developers, Current page does not respond with a 200 when offline

Good abstractions make complex APIs easier to use. That’s where Workbox comes in.

— Google Chrome Developers, What is Workbox?

You can add Workbox via build tools (workbox-webpack-plugin, workbox-build, workbox-cli), bundle modules in the service worker, or load workbox-sw from the CDN. For registration and update UX on the page, use workbox-window.

Service worker lifecycle: register, install, activate, control

Section titled “Service worker lifecycle: register, install, activate, control”

Understanding lifecycle behavior answers most “why doesn’t my new worker run yet?” questions.

It’s hard to know what service workers are doing without understanding their lifecycle.

— Google Chrome Developers, A service worker’s life

Registration: HTTPS, scope, and when to call register()

Section titled “Registration: HTTPS, scope, and when to call register()”

Registration uses navigator.serviceWorker.register(). Service workers are only available over HTTPS or localhost. Syntax errors during registration cause the worker to be discarded.

Service workers are only available over HTTPS or localhost.

— Google Chrome Developers, A service worker’s life

Scope is the directory of the service worker URL (for example /subdir/sw.js controls /subdir/). Scope limits which clients (controlled pages) the worker owns—not which URLs it may intercept in fetch (cross-origin assets can still be handled). Widen scope with the Service-Worker-Allowed response header or the scope option on register(). Chrome recommends serving the service worker from the site root unless you have a strong reason to narrow scope. See A service worker’s life.

If you precache at install, registration timing affects bandwidth: registering after the window load event avoids competing with critical assets (deployment expectations).

If a service worker precaches anything, then the time at which it’s registered matters.

— Google Chrome Developers, Expectations around service worker deployment

workbox-window’s Workbox.register() waits for load by default, matching that guidance.

Install, activate, and why refresh is often required

Section titled “Install, activate, and why refresh is often required”

For a brand-new worker: register → install (install event, use event.waitUntil) → activate → control. By default a newly installed worker does not control the current page until the next navigation or full reload.

Notice that, by default, the new service worker won’t begin controlling the page until the next navigation or page refresh.

— Google Chrome Developers, A service worker’s life

The first time a worker is installed, it also will not control the open page unless the worker calls clients.claim() in activate (workbox-window).

Updates: two versions, waiting, and skipWaiting()

Section titled “Updates: two versions, waiting, and skipWaiting()”

An update is detected when the registered script URL’s contents change (same URL and scope—do not rename the SW file or HTTP-cache the script). Navigation within scope, another register() call, and some background events can trigger update checks (lifecycle).

When an update installs, the old worker keeps controlling open tabs; the new one enters waiting until no clients remain on the old version—unless you call self.skipWaiting().

You can speed up activation of updated service workers by calling self.skipWaiting, but this may be a bad idea.

— Google Chrome Developers, A service worker’s life

skipWaiting() can leave lazy-loaded subresources on a stale combination until the next navigation. For user-controlled updates, see Handling service worker updates and workbox-window’s waiting event plus messageSkipWaiting() (workbox-window).

On activate, delete outdated caches (caches.keys() and an allow list). After Workbox major upgrades, cleanupOutdatedCaches() from workbox-precaching avoids duplicate precache entries.

Approach When it runs Typical use
Precache install (manifest from build) App shell, critical CSS/JS, offline HTML, hashed static files
Runtime cache On each matching fetch Large, rare, language-varying, or unbounded sets of URLs

workbox-precaching deduplicates manifest URLs, stores revisioned cache keys, serves precached URLs cache-first via precacheAndRoute() (call it before other routes), and removes manifest entries no longer listed on activate. Do not hardcode revisions—use precaching with Workbox build output. Precaching dos and don’ts: do precache critical static assets and offline fallbacks where needed; avoid precaching every HTML page on large changing sites or polyfills you may never need.

Runtime routing is covered in caching resources during runtime and workbox-routing.

Caching strategies: Cache First, Network First, and Stale While Revalidate

Section titled “Caching strategies: Cache First, Network First, and Stale While Revalidate”

The Cache interface is a caching mechanism entirely separate from the HTTP cache.

— Google Chrome Developers, Strategies for service worker caching

workbox-strategies implements the common patterns (strategies overview):

Strategy Behavior Typical use
CacheOnly Cache only Rare; precached assets
NetworkOnly Network only Fresh APIs, default passthrough
CacheFirst Cache, else network Versioned static files, images
NetworkFirst Network, else cache HTML, frequently updated content
StaleWhileRevalidate Cache immediately; always revalidate in background Semi-fresh assets (avatars, CSS/JS with SWR)

Workbox’s StaleWhileRevalidate always sends a revalidation request, unlike some stale-while-revalidate implementations that skip revalidation by age (workbox-strategies).

Opaque responses (no-cors cross-origin) are cached cautiously by default. Prefer NetworkFirst or StaleWhileRevalidate for opaque assets; blind CacheFirst with CacheableResponsePlugin({ statuses: [0, 200] }) can persist error responses (runtime caching).

Set cacheName per strategy for debugging. ExpirationPlugin (maxAgeSeconds, maxEntries) requires an explicit cacheName (workbox-expiration, storage quota).

Version unversioned JS at runtime with CacheFirst and users can keep stale app.js forever—use hashed filenames, precache manifests, or NetworkFirst/SWR (deployment).

registerRoute, NavigationRoute, and default handlers

Section titled “registerRoute, NavigationRoute, and default handlers”

When a network request causes a service worker fetch event, workbox-routing will attempt to respond to the request using the supplied routes and handlers.

— Google Chrome Developers, workbox-routing

Rules from workbox-routing:

  • Routes handle GET by default; other methods need explicit setup.
  • First registered matching route wins.
  • Match callbacks must return synchronously (no async match).
  • Prefer request.destination and request.mode === 'navigate' over file extensions.

NavigationRoute sends navigations to a handler—often a precached app shell via createHandlerBoundToURL() (app shell model). Use allowlist / denylist; denylist wins if both match.

setDefaultHandler handles unmatched requests. setCatchHandler runs when a route throws—used by offline fallback patterns (managing fallback responses).

For cross-origin RegExp routes, anchor the full URL so you do not accidentally match third-party URLs.

workbox-recipes: when recipes beat hand-written routes

Section titled “workbox-recipes: when recipes beat hand-written routes”

workbox-recipes bundles routing + strategies + plugins for common setups:

A number of common patterns, especially around routing and caching, are common enough that they can be standardized into reusable recipes.

— Google Chrome Developers, workbox-recipes

Recipe Strategy (default) Notes
pageCache() NetworkFirst, 3s timeout Navigations; LCP-oriented defaults
staticResourceCache() StaleWhileRevalidate style, script, worker
imageCache() CacheFirst 60 entries, 30 days
googleFontsCache() SWR + CacheFirst Stylesheet vs gstatic files
offlineFallback() Catch by destination Default page offline.html
warmStrategyCache() User-chosen Warm URLs at install

Combining pageCache, staticResourceCache, imageCache, googleFontsCache, and offlineFallback yields network-first pages, SWR for scripts/styles, cache-first images, font handling, and offline page fallback (workbox-recipes).

offlineFallback() alone does not create routes:

The offline fallback will only be applied if there’s a matching route for a given request. If you’re using the offline fallback recipe on its own, you’ll need to create routes yourself.

— Google Chrome Developers, workbox-recipes

Minimal pattern: setDefaultHandler(new NetworkOnly()) then offlineFallback().

Loading Workbox with workbox-sw and building with webpack

Section titled “Loading Workbox with workbox-sw and building with webpack”

Classic service workers without a bundler can use workbox-sw:

importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.4.1/workbox-sw.js');

Lazy-loaded modules trigger extra importScripts only during synchronous top-level execution or inside the install handler—not on first use inside an async fetch handler without prior workbox.loadModule() (workbox-sw).

workbox-webpack-plugin:

Plugin Use when
GenerateSW Precache plus simple runtimeCaching; no heavy custom SW logic
InjectManifest Custom swSrc, Web Push, or full control of routing

Do not use GenerateSW when you need to import extra scripts or substantial custom strategy code—use InjectManifest instead (when not to use GenerateSW).

generateSW vs injectManifest and precaching with Workbox cover CLI and workbox-build paths.

workbox-window: registration, events, and messaging

Section titled “workbox-window: registration, events, and messaging”

workbox-window surfaces lifecycle moments (installed, waiting, controlling, activated) and reduces scope mistakes.

import {Workbox} from 'https://storage.googleapis.com/workbox-cdn/releases/6.4.1/workbox-window.prod.mjs';
const wb = new Workbox('/sw.js');
wb.addEventListener('waiting', () => { /* prompt user */ });
wb.register();

Add listeners before register(). Use controlling (not activated alone) to know the page is controlled. messageSW({ type, payload }) talks to the worker over a MessageChannel; pair with BroadcastUpdatePlugin for CACHE_UPDATED messages (plugins, workbox-broadcast-update).

For waiting workers, messageSkipWaiting() sends { type: 'SKIP_WAITING' }; the service worker must listen and call self.skipWaiting() (handling updates).

Section titled “Navigation preload, timeouts, and offline fallbacks”

Navigation preload starts the navigation network request in parallel with service worker boot—helpful when HTML is not precached and navigations use NetworkFirst/NetworkOnly. Do not enable it when a precached app shell always serves navigations (navigation preload). You must register a navigation route that uses the preloaded response.

Warning: If you don’t register a route to handle the preloaded response using a network-first (or even a network only) strategy, the preloaded response will go unused.

— Google Chrome Developers, Navigation Preload for Network-first HTML

networkTimeoutSeconds on NetworkFirst/NetworkOnly caps wait time before cache fallback (forcing a network timeout).

Offline UX: precache /offline.html, use PrecacheFallbackPlugin with NetworkOnly navigations, or recipe/setCatchHandler patterns in managing fallback responses. MPAs vs SPAs: different architectures; streaming partials via workbox-streams is optional advanced material.

You can use the Cache API from the window for “save for offline” without every feature living in the worker (access caches from the window).

Development, Lighthouse PWA checks, and recovery

Section titled “Development, Lighthouse PWA checks, and recovery”

Local dev: localhost is secure; use DevTools Application → Service Workers and Cache Storage; incognito mimics lifecycle cleanly (improving development experience). Shift+reload bypasses the worker once. Do not treat DevTools “Update on reload” as production lifecycle behavior.

Lighthouse expects a controlling service worker and offline 200 for the start URL when auditing PWA criteria (service worker audit, works offline, offline start URL).

If a deployed worker is broken, ship a no-op worker at the same URL with skipWaiting and no fetch handler:

It’s very important that a no-op service worker contains no fetch event handler.

— Google Chrome Developers, Removing buggy service workers

  • Registering before load while precaching large manifests (deployment).
  • Default webpack precache including too many assets (deployment).
  • Runtime CacheFirst on unversioned app.js.
  • offlineFallback() without routes or setDefaultHandler(NetworkOnly).
  • Async match callbacks in custom routes (workbox-routing).
  • First workbox.* use inside fetch without top-level load when using workbox-sw.
  • Enabling navigation preload with an unconditional precached shell (navigation preload).
  • HTTP-caching or renaming the service worker script file (lifecycle).
  • ExpirationPlugin without cacheName on the strategy.
  • Video/audio without crossorigin and RangeRequestsPlugin (serving cached audio and video).
  1. Open Chrome DevTools → Application → Service Workers and confirm state (installing, waiting, activated) and scope for your sw.js URL.

  2. Inspect Cache Storage for Workbox cache names (pages, precache prefix, recipe caches) and that revisions update after a deploy (workbox-precaching).

  3. Enable Offline in DevTools, reload, and verify navigations and assets match your strategies (caching strategies overview).

  4. Run Lighthouse PWA audits for service worker registration and offline start URL.

  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact sentence you are asking about, and we will correct or clarify it.