Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 37 ยท Installability and Distribution

Updating a PWA Safely

Ship PWA updates without breaking users: the update check, waiting workers, skipWaiting trade-offs, an update toast, cache versioning, cleanup and a kill switch.

A website updates the moment you deploy: the next page load fetches new files. A PWA is different. Its service worker and caches live on the device, so the user may keep running last month's code for a long time unless you design the update path. Done carelessly, users get stuck on old versions, see broken pages when new HTML meets old JavaScript, or lose unsaved work to a surprise reload.

This lesson explains how the browser detects a new worker, why a new worker waits, how to tell the user, how to clean old caches, and what to do in an emergency. The install and activate events themselves are covered in install and activate events; here the focus is on the whole update experience.

How the browser finds an update

Each time a page in your scope loads (and at least every 24 hours for long-lived installed apps), the browser re-fetches the service worker script, bypassing the HTTP cache for that one file by default. If the bytes differ from the current script, a new worker starts installing next to the old one.

sequenceDiagram
  participant B as Browser
  participant Old as Active worker v1
  participant New as New worker v2
  B->>B: fetch sw.js, bytes changed
  B->>New: install (precache v2 assets)
  Note over New: state: installed (waiting)
  Note over Old: still controls open pages
  New-->>B: waits until all v1 pages close
  B->>New: activate (delete old caches)

The new worker waits so that open pages never switch code in the middle of a session.

Only the worker file itself is compared. Changing a cached asset such as app.js does not trigger an update by itself, which is why most build tools inject a revision or hash into sw.js whenever any precached file changes.

Two practical rules:

  • Never let sw.js itself be cached for long. Serve it with Cache-Control: no-cache (or a very short max-age).
  • Do not rename it per version; the worker URL must stay stable, because it identifies the registration.

Waiting and skipWaiting

By default the new worker activates only after every tab using the old worker is closed. That is safe, but many users keep the installed app in the background for days. Calling self.skipWaiting() in install makes the new worker take over immediately.

Immediate takeover is simple but risky: the page already running was built for v1 assets and may request files that v2's cleanup just deleted. The safer pattern is user-controlled update: detect the waiting worker, tell the user, and activate it on request.

JavaScript
// page code (read-only: needs a real registration)
const registration = await navigator.serviceWorker.register("/sw.js");

function showUpdateToast(worker) {
  toast("A new version is ready.", {
    action: "Reload",
    onAction: () => worker.postMessage({ type: "SKIP_WAITING" }),
  });
}

if (registration.waiting) showUpdateToast(registration.waiting);

registration.addEventListener("updatefound", () => {
  const installing = registration.installing;
  installing.addEventListener("statechange", () => {
    if (installing.state === "installed" && navigator.serviceWorker.controller) {
      showUpdateToast(installing);   // there was an old worker, so this is an update
    }
  });
});

let reloading = false;
navigator.serviceWorker.addEventListener("controllerchange", () => {
  if (reloading) return;
  reloading = true;
  location.reload();
});
JavaScript
// sw.js
self.addEventListener("message", (event) => {
  if (event.data?.type === "SKIP_WAITING") self.skipWaiting();
});

The check navigator.serviceWorker.controller separates a first install (no controller, no toast needed) from an update. The reloading flag prevents a reload loop when several events fire.

Try it: the update state machine

The sequence has several states, and different actions are right in each. This stand-in models a registration and lets you walk through a deploy:

JS Walking through an update

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Version your caches and clean up

Cache names carry a version so a new worker can fill fresh caches while the old one still serves from the old:

JavaScript
const PRECACHE = "precache-v7";
const RUNTIME = "runtime-v1";   // only bump when its format changes

self.addEventListener("activate", (event) => {
  event.waitUntil(
    (async () => {
      const keep = new Set([PRECACHE, RUNTIME]);
      for (const name of await caches.keys()) {
        if (!keep.has(name)) await caches.delete(name);
      }
      await self.clients.claim();
    })()
  );
});

Delete in activate, not in install: during install the old worker is still serving pages that need the old cache.

JS Which caches survive?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Practical update tips

  • Hash your static files (app.3f9a1c.js). New file names never collide with cached old files, and old pages keep working because their files still exist until cleanup.
  • Precache with revisions. Workbox's precacheAndRoute compares revisions and downloads only changed files.
  • Check for updates on a timer in long-lived sessions: setInterval(() => registration.update(), 60 * 60 * 1000).
  • Never skipWaiting during a form or an unsaved edit. If you must update eagerly, save state first or wait for a safe moment such as navigation.
  • Test the upgrade path from the previous release, not only fresh installs. Keep a script that installs vN-1, deploys vN and checks the result.

The kill switch

Sooner or later a bad worker ships, for example one that caches an error page forever. Plan the escape route before you need it:

  1. Keep sw.js uncacheable so a fix can reach everyone.
  2. Deploy a replacement worker that deletes all caches, unregisters itself and reloads clients:
JavaScript
// emergency sw.js
self.addEventListener("install", () => self.skipWaiting());
self.addEventListener("activate", (event) => {
  event.waitUntil(
    (async () => {
      for (const name of await caches.keys()) await caches.delete(name);
      await self.registration.unregister();
      const windows = await self.clients.matchAll({ type: "window" });
      windows.forEach((client) => client.navigate(client.url));
    })()
  );
});

Also consider a server-side flag or a small /version.json fetched with cache: "no-store" that your page compares to its built-in version to prompt a hard refresh.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the browser compare to detect an update?

    A byte difference in the worker script starts an update; changed cached assets alone do not.
  2. 2. Why does a new worker wait instead of activating at once?

    Waiting keeps each page consistent with the code it was loaded with.
  3. 3. Where should old caches be deleted?

    In activate the old worker is gone, so deleting its caches cannot break pages it is still serving.
  4. 4. Why serve sw.js with no-cache?

    A long-cached worker script delays updates and makes emergencies much worse.

Summary

  • Updates start when the worker script's bytes change; keep sw.js uncached and its URL stable.
  • A new worker waits; let the user trigger activation with a toast and SKIP_WAITING, then reload on controllerchange.
  • Version cache names, clean up in activate, and hash static assets.
  • Test upgrades from the previous release and prepare a kill-switch worker.

Next: Store Distribution: TWA, PWABuilder and More