DEV Community

Cover image for Versioned service worker caches: install new, fetch current, clean up narrowly
Chris Rodriguez
Chris Rodriguez

Posted on Originally published at chriseugenerodriguez.com

Versioned service worker caches: install new, fetch current, clean up narrowly

A service worker update is safer when cache ownership is explicit. Rather than reusing one permanent cache name, assign each worker revision its own cache generation, such as an application prefix plus a version. The cache name then becomes part of the active worker’s contract.

Use the lifecycle phases for separate jobs. During install, open the new versioned cache and precache the selected application resources, including the offline page. Do not remove previous generations here: installation can fail, and older clients may still be controlled by the prior worker. During activate, enumerate cache names and remove only names that share the application’s prefix but are not the current name. This preserves unrelated cache families.

For fetch handling, keep the fallback deliberately narrow. Let HTML GET requests try the network first. If the network fails, open the current version’s cache and look up the configured offline page there. Do not search all caches. A global search can allow a newly active worker to serve an old offline document simply because that cache has not yet been removed.

The expected result is a clean handoff: the new cache is prepared before old versioned caches are retired, offline navigation resolves from the current generation, and unrelated caches remain untouched. If the current cache lacks its offline response, failing is often safer than hiding a deployment error with stale content.

There is an important proof boundary. A fixture with injected CacheStorage-like dependencies can verify naming, cleanup selection, request filtering, and fallback control flow. It cannot verify actual browser scheduling, registration timing, or service worker event behavior. Wire the same lifecycle logic into real install, activate, and fetch handlers, then validate that integration in a browser—especially if navigation preload, skipWaiting, or clients.claim are involved.

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")
  );
}
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)