Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Service Worker Offline Fallback

Last updated: 5 Oct 20266 min read
tutorial
IntermediateBy AITrove Editorial

A service worker can intercept eligible requests under its scope and choose a response from the network or a local cache. That power requires a narrow policy. Cache the public application shell and an offline explanation page during installation; do not place authenticated case HTML or API responses into a shared-looking cache by default. Update caches by version and remove obsolete entries during activation. A worker may be stopped between events, so state that must persist belongs in storage, not a global variable. The offline page should explain what remains available and what requires reconnecting.

Working case

An inspector opens the public guide while online, then loses connectivity on a train. The installed worker can serve a previously cached guide shell and an offline message. It must not silently show an old private case as though it were current. A case submission remains pending until a server confirms it. The example handles only a named public guide and an offline page; every other request follows normal browser behavior. A production worker also needs versioned asset lists and upgrade tests across old and new tabs.

Implementation

javascript
const shellCache = "guide-shell-v3";
const offlinePage = "/offline";
self.addEventListener("install", event => {
  event.waitUntil(caches.open(shellCache).then(cache =>
    cache.addAll(["/guides/inspection", offlinePage])));
});
self.addEventListener("activate", event => {
  event.waitUntil(caches.keys().then(keys => Promise.all(
    keys.filter(key => key.startsWith("guide-shell-") && key !== shellCache)
      .map(key => caches.delete(key)))));
});
self.addEventListener("fetch", event => {
  const target = new URL(event.request.url);
  if (event.request.method !== "GET" || target.pathname !== "/guides/inspection") return;
  event.respondWith(fetch(event.request).catch(async () =>
    await caches.match(event.request) ?? await caches.match(offlinePage)));
});

Cost and boundaries

Caching public shell bytes consumes O(B) local storage for B cached bytes and adds install-time transfer. Each intercepted request adds a small lookup and policy decision; a network-first strategy can still wait on a failing connection unless timeout behavior is defined. Keeping too many revisions wastes device storage and can lead to eviction. Test update and rollback paths, not only first install. A service worker is useful only when it improves a real offline journey.

Common Mistakes

  • Do not cache private case responses without an explicit privacy policy.
  • Do not assume a worker stays alive between events.
  • Do not label a stale record as current while offline.

Connected lessons

Offline and Device Capabilities; IndexedDB for Local Drafts; Web App Manifest and Optional Installation; Offline Sync and Conflict Policy; Browser storage: save convenience data without storing credentials; Fetch requests: separate HTTP failure, transport failure, and cancellation; HTTP caching: validate a changed representation with an ETag.

Failure trace

A worker caches the login response under a broad path rule. After user A signs out, user B opens the site offline and sees user A's private case summary. An offline shell must not include account data from a previous session. Cache only explicitly public assets and a safe fallback page; let private responses follow a separate policy and clear account-bound local state on sign-out.

Verification

  • Load a public guide offline and verify a useful fallback or cached copy appears.
  • Switch accounts on one browser profile and confirm no prior private response is served from storage.
  • Install a new worker version and test how old caches are removed without breaking active tabs.

Decision note

A service worker intercepts requests but cannot manufacture current server truth. State what remains available offline and which operations are queued, blocked, or require a fresh authorization check.

Apply and check

Build Project: offline inspection draft and photo intake; then check the boundary with Web Development: offline and delivery contracts quiz.

Further connections

Wasm Loading, Artifact, and Fallback Contract.

Further connections

Offline Storage and Upgrade Safety; Service Worker Activation and Unsent Work.

web-tech
web-development
Storage details