Service Worker Lifecycle And Updates

Service worker updates are where many PWAs break after the first successful demo.

Update Model

  1. Browser checks the service worker script for byte changes.
  2. New worker installs.
  3. If existing controlled clients are open, the new worker waits.
  4. It activates after old clients close, or earlier if you call skipWaiting().
  5. Activated worker controls future pages, or existing pages after clients.claim().

Safe Update UX

if ('serviceWorker' in navigator) {
  const registration = await navigator.serviceWorker.ready;

  registration.addEventListener('updatefound', () => {
    const worker = registration.installing;
    worker?.addEventListener('statechange', () => {
      if (worker.state === 'installed' && navigator.serviceWorker.controller) {
        showUpdateAvailableToast();
      }
    });
  });
}

Cache Migration Rules

  • Cache names include a version.
  • Activation deletes old cache versions.
  • HTML is not cached forever.
  • JS and CSS are fingerprinted by the build.
  • Update prompt reloads all app tabs or clearly warns the user.
  • Outbox and user data migrations are separate from asset cache cleanup.

Gotcha: skipWaiting() plus clients.claim() can be correct for simple apps, but it can also put old pages under a new worker. Use it only with an update strategy you have tested.