Service Worker Cache Routing, Strategies, and Plugin Lifecycle
How Workbox routes fetch requests, chooses cache strategies, and runs plugin callbacks—and how that compares to edge worker cache APIs.
Most of this page follows Chrome’s Workbox module documentation: libraries that sit on the Service Worker API and decide which requests to intercept, whether to read the Cache Storage API or the network first, and which hooks run around each step. A smaller part of the cluster covers Cloudflare Workers programmatic cache and fetch() cache modes—same Request/Response objects, different runtime.
Fetch events: what triggers a service worker handler
Section titled “Fetch events: what triggers a service worker handler”In a browser extension service worker, the fetch event fires when resources are loaded from the extension package or when fetch() and XMLHttpRequest() run from an extension or popup script—not from content scripts.
Fired when anything is retrieved from the extension package or when fetch() and XMLHttpRequest() are called from an extension or popup script. (Calls from content scripts are not intercepted by the service worker fetch handler.)
— Chrome, Events in service workers
In Workbox, the Router connects those fetch events to registered routes. On Cloudflare Workers, the analogous surface is FetchEvent with event.request, event.respondWith(), event.waitUntil(), and event.passThroughOnException()—always event.type === "fetch".
Common conclusion: Something must listen for fetches and call respondWith() (or Workbox’s Router.handleRequest) if you want custom caching; unmatched requests behave like no service worker unless a default handler is set.
workbox-routing: how requests match a cache handler
Section titled “workbox-routing: how requests match a cache handler”Workbox routing pairs a match callback (does this URL/method apply?) with a handler that returns a Promise<Response>.
A Route consists of a pair of callback functions, “match” and “handler”. The “match” callback determine if a route should be used to “handle” a request by returning a non-falsy value if it can. The “handler” callback is called when there is a match and should return a Promise that resolves to a Response.
— Chrome, workbox-routing
GET vs POST: registering routes by HTTP method
Section titled “GET vs POST: registering routes by HTTP method”Routes default to GET only. Non-GET traffic needs an explicit method when you register the route:
import {registerRoute} from 'workbox-routing';
registerRoute(matchCb, handlerCb, 'POST');registerRoute(new RegExp('/api/.*\\.json'), handlerCb, 'POST');— pattern from Defining a Route for Non-GET Requests
In Workbox v6, setDefaultHandler() also takes an optional HTTP method (default 'GET'). If you relied on the default handler for all methods, only GET still matches unless you register handlers per method (migrate-from-v5).
Router behavior: first match, defaults, and errors
Section titled “Router behavior: first match, defaults, and errors”If a request matches multiple routes, the earliest registered route will be used to respond to the request.
— Chrome, workbox-routing — Router
Without a default handler, unmatched requests will go against the network as if there were no service worker present.
— Chrome, setDefaultHandler
If a route throws, the router can use a catch handler. registerRoute() is the usual shortcut: string, RegExp, match function, or full Route plus a strategy or custom handler.
NavigationRoute matches only requests whose mode is navigate, with optional allowlist/denylist on pathname + search. Chrome warns that complex regexps on every navigation can slow the site.
workbox-strategies: when to use cache-first vs network-first
Section titled “workbox-strategies: when to use cache-first vs network-first”Strategies implement the handler side: cache name, matchOptions, fetchOptions, plugins, and optional expiration (Configuring Strategies).
| Strategy | Typical use | Failure if empty cache / network down |
|---|---|---|
| CacheFirst | Revisioned static assets (e.g. hashed CSS) | Throws WorkboxError if no cache and network fails |
| StaleWhileRevalidate | Fast response + background refresh | Throws if both fail |
| NetworkFirst | HTML/API where freshness matters; optional networkTimeoutSeconds |
Falls back to cache, else throws |
| NetworkOnly / CacheOnly | Strict online-only or offline-only paths | Network or cache failure throws |
A cache first strategy is useful for assets that have been revisioned, such as URLs like /styles/example.a8f5f1.css, since they can be cached for long periods of time.
— Chrome, CacheFirst
Resources are requested from both the cache and the network in parallel. The strategy will respond with the cached version if available, otherwise wait for the network response. The cache is updated with the network response with each successful request.
— Chrome, StaleWhileRevalidate
Custom strategies should call StrategyHandler methods (handler.fetch(), handler.cacheMatch(), handler.cachePut(), handler.fetchAndCachePut()) so plugins run—not raw fetch() alone (Creating A New Strategy).
Plugins and lifecycle: cacheWillUpdate, fetchDidSucceed, and handler callbacks
Section titled “Plugins and lifecycle: cacheWillUpdate, fetchDidSucceed, and handler callbacks”A Workbox plugin is an object with optional async callbacks. When attached to a Strategy, they run at defined points (Using plugins, WorkboxPlugin).
Cache-oriented callbacks
cacheKeyWillBeUsed— normalize or override the key (modeis'read'or'write').cacheWillUpdate— allow, replace, or block storing a response (nullskips the update).cachedResponseWillBeUsed— swap or drop a cached hit before it is served.cacheDidUpdate— run after the cache entry changes (e.g. broadcast update).
Network-oriented callbacks
requestWillFetch— mutate the request immediately before the network (clone the body here if later callbacks need it).fetchDidSucceed/fetchDidFail— success includes non-OK HTTP codes;fetchDidFailis for connectivity-style failures, not every 404.
Handler callbacks (Workbox v6+)
handlerWillStart: called before any handler logic starts running… handlerDidComplete: called after all extend lifetime promises added to the event from the invocation of this strategy have settled.
— Chrome, Migrate from Workbox v5 to v6
handlerDidError is the hook for fallback responses when no valid response exists—PrecacheFallbackPlugin uses it to serve a precached offline page.
In v6, each plugin gets a per-invocation state object shared across that plugin’s callbacks on one handle() call (migration guide), so you can measure latency or pass data between requestWillFetch and fetchDidSucceed.
StrategyHandler#waitUntil extends the fetch event lifetime; use doneWaiting() before work that is not tied to the handler’s own waitUntil queue.
Built-in plugins you configure in workbox-build
Section titled “Built-in plugins you configure in workbox-build”workbox-build runtime caching entries can attach shortcuts: expiration, cacheableResponse, broadcastUpdate, backgroundSync, rangeRequests, precacheFallback, plus custom plugins. Each route needs urlPattern, handler (strategy name or custom function), and optional method (default "GET").
CacheableResponsePlugin runs cacheWillUpdate logic: if both statuses and headers are set, both must pass.
ExpirationPlugin needs a custom cacheName on the strategy—not the default runtime cache. It can set purgeOnQuotaError (see storage quota): marking runtime caches safe to drop helps recovery when storage is tight.
workbox-precaching: install-time cache and revision keys
Section titled “workbox-precaching: install-time cache and revision keys”Precaching lists assets at install, serves them via a dedicated route, and versions keys (e.g. __WB_REVISION__ query params). matchPrecache('index.html') resolves the active revision without you passing the full cache key.
precacheAndRoute() combines precache() and addRoute(). Requests for URLs not in the manifest fall through to other listeners (addRoute). Call activate cleanup to drop obsolete entries; cleanupOutdatedCaches() helps after upgrades.
workbox-recipes bundles common patterns (pageCache, imageCache, offlineFallback, etc.) on top of routing + strategies.
Cloudflare Workers Cache API vs browser Cache Storage
Section titled “Cloudflare Workers Cache API vs browser Cache Storage”On a Worker, the Cache API is keyed by Request (or URL string):
Attempts to add a response to the cache, using the given request as the key. Returns a promise that resolves to undefined regardless of whether the cache successfully stored the response.
— Cloudflare, Cache — Put
The stale-while-revalidate and stale-if-error directives are not supported when using the cache.put or cache.match methods.
— Cloudflare, Cache
cache.delete() only purges the current data center; global purge needs separate purge APIs (Cache — Delete). match/delete accept ignoreMethod: true to treat the key as GET.
Worker fetch() supports only cache: 'no-store' and cache: 'no-cache'; other modes throw Unsupported cache mode. Both modes affect how non-Cloudflare origins revalidate or bypass Cloudflare’s edge cache—different from Workbox’s browser runtime caches.
Common mistakes
Section titled “Common mistakes”- Expecting POST to hit
setDefaultHandler()or implicit GET routes after upgrading to Workbox v6. - Attaching
ExpirationPluginwithout a dedicatedcacheNameon the strategy. - Reading
request.bodyin late plugin callbacks after the strategy already consumed it—clone inrequestWillFetchand stash instate(Using plugins). - Using
BroadcastUpdatePluginon opaque responses: headers are invisible, so updates are never detected (workbox-broadcast-update). - Assuming
cache.delete()on a Worker clears cache globally (Cloudflare Cache). - Calling raw
fetch()inside a custom strategy instead ofStrategyHandler#fetch, skipping plugin hooks.
How to check this on your site
Section titled “How to check this on your site”- In Chrome DevTools → Application → Service Workers, confirm your script is active and “Offline” behavior matches your strategy (e.g. NetworkFirst still serves cached fallbacks).
- Under Cache Storage, inspect Workbox cache names (
cacheNamesfrom workbox-core: precache, runtime, googleAnalytics) and verify entries expire or update as configured. - Trigger a navigation and a
POSTAPI call; in the Network panel, confirm only intended routes are handled (GET-only defaults from workbox-routing). - For precaching, load a revisioned asset URL and confirm
matchPrecachebehavior via your offline shell (workbox-precaching). - On Cloudflare Workers, use observability traces that include
cache.request.*/cache.response.*attributes (Spans and attributes) afterput,match, ordelete.
You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact statement you are asking about.