Reviewing a stale offline-page failure in service worker cache updates

Reviewing a stale offline-page failure in service worker cache updates

●2 ●48
calendar_today ago • schedule3 min read
— Originally published at chriseugenerodriguez.com

A cache update can fail in a subtle way: the new worker is active, the network is unavailable, and the offline response comes from an old cache—or no cache at all. The failure is usually caused by treating CacheStorage as one shared bucket instead of a set of version-owned resources.

Prerequisites: decide on an application-specific cache prefix, a revision value for each deployment, one offline document, and the list of resources that must be precached. The prefix is important because cache storage may contain names owned by unrelated features.

The implementation decision is to give each revision its own name. The install path opens only the current version’s cache and fills it with the offline page and other chosen resources. The activate path lists cache names, then deletes only prefixed names that are not the current version. It must not clear all CacheStorage entries.

For navigation handling, restrict offline fallback to HTML GET requests. Attempt the network first. Only after failure should the worker open the current cache and request its configured offline URL. This is a stronger rule than “find an offline page somewhere”: an old cache is not an acceptable substitute for the active worker’s expected asset.

The expected result is a predictable transition. The prior generation remains available while the new generation is prepared; after activation, obsolete caches in the same namespace are retired; and offline navigation uses the current version’s page. A missing page in that current cache stays visible as an error rather than being masked by stale content.

One limitation remains: an injected recording or in-memory cache dependency can demonstrate the selection and fallback rules, but it is not a browser service worker runtime. Confirm real install, activate, and fetch wiring in a browser, particularly when using lifecycle controls such as skipWaiting or clients.claim.

Working example

export const proofBoundary =
  "This module orchestrates CacheStorage-like dependencies. Its Node tests prove the version naming, cleanup selection, and fallback control flow only; run the lifecycle through a real service worker in a browser to verify install, activate, Cache.addAll(), and Cache.match() behavior.";

/**
 * Builds the logic called by a service worker's install, activate, and fetch
 * handlers. The caller supplies the browser's `caches` object and `fetch`.
 */
export function createVersionedCacheLifecycle({
  cacheStorage,
  cachePrefix,
  version,
  offlineUrl,
  precacheUrls,
}) {
  if (!cacheStorage || typeof cacheStorage.open !== "function") {
    throw new TypeError("cacheStorage.open must be a function");
  }
  if (!cacheStorage || typeof cacheStorage.keys !== "function") {
    throw new TypeError("cacheStorage.keys must be a function");
  }
  if (typeof cachePrefix !== "string" || cachePrefix.length === 0) {
    throw new TypeError("cachePrefix must be a non-empty string");
  }
  if (typeof version !== "string" || version.length === 0) {
    throw new TypeError("version must be a non-empty string");
  }
  if (typeof offlineUrl !== "string" || offlineUrl.length === 0) {
    throw new TypeError("offlineUrl must be a non-empty string");
  }
  if (!Array.isArray(precacheUrls) || !precacheUrls.includes(offlineUrl)) {
    throw new TypeError("precacheUrls must include offlineUrl");
  }

  const cacheName = `${cachePrefix}${version}`;

  return {
    cacheName,

    // Call from: event.waitUntil(lifecycle.install())
    async install() {
      const cache = await cacheStorage.open(cacheName);
      await cache.addAll(precacheUrls);
    },

    // Call from: event.waitUntil(lifecycle.activate())
    async activate() {
      const names = await cacheStorage.keys();
      const obsoleteNames = names.filter(
        (name) => name.startsWith(cachePrefix) && name !== cacheName,
      );
      await Promise.all(obsoleteNames.map((name) => cacheStorage.delete(name)));
    },

    // Call from: event.respondWith(lifecycle.respondToFetch(event.request, fetch))
    async respondToFetch(request, fetchFunction) {
      if (!isHtmlGetRequest(request)) {
        return fetchFunction(request);
      }

      try {
        return await fetchFunction(request);
      } catch {
        const cache = await cacheStorage.open(cacheName);
        const offlineResponse = await cache.match(offlineUrl);
        if (offlineResponse !== undefined) {
          return offlineResponse;
        }
        throw new Error(`Offline response is missing from ${cacheName}`);
      }
    },
  };
}

function isHtmlGetRequest(request) {
  return (
    request?.method === "GET" &&
    typeof request.headers?.get === "function" &&
    request.headers.get("accept")?.includes("text/html")
  );
}

Read the full article: https://chriseugenerodriguez.com/blog/how-do-i-update-a-service-worker-cache-and-delete-old-versions-safely

Want more #programming deep dives?

Join 5,982+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

1 Comment

0 votes

More Posts

I’m a Senior Dev and I’ve Forgotten How to Think Without a Prompt

Karol Modelski - Mar 19

Frameworks Are Institutional Memory

Ken W. Algerverified - Sep 17

TypeScript Complexity Has Finally Reached the Point of Total Absurdity

Karol Modelski - Apr 23

Your Tech Stack Isn’t Your Ceiling. Your Story Is

Karol Modelski - Apr 9

A Message From Our Founder: On the Winding Down of LaaSy™

Ken W. Algerverified - Oct 29
chevron_left
987 Points • 50 Badges
Santa Monica, CA • chriseugenerodriguez.com
37Posts
0Comments
8Connections
10 years fe

Related Jobs

View all jobs →

Commenters (This Week)

26 comments
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!