Dev.to WebDev πŸ›  Dev πŸ‘ 0 πŸ“– 9 min read

The PWA Update Trap: Why Users Get Stuck on Old Releases and How to Ship Safely

You ship a release. A user opens your installed PWA and sees last week's UI. You reload, it still shows last week's UI, and clearing the cache "fixes" it, which is the worst possible support answer. The cause is rarely

The PWA Update Trap: Why Users Get Stuck on Old Releases and How to Ship Safely

You ship a release. A user opens your installed PWA and sees last week's UI. You reload, it still shows last week's UI, and clearing the cache "fixes" it, which is the worst possible support answer.

The cause is rarely one bug. It's an interaction between three things: how the HTML document is cached, how the service worker is versioned, and which asset files exist after a deploy. This post reproduces three failures with a two-release lab, then shows the deploy pattern that avoids them.

TL;DR

  • A service worker update is detected by a byte difference, then installs and waits. A page reload does not release it.
  • Cache First for the HTML document, a worker URL that changes per release, and unconditional skipWaiting() each create a different failure.
  • The safer pattern: Network First navigation, a stable worker URL, a user-consented skipWaiting(), and keeping the previous release's cache for open tabs.
  • Everything below ran in headless Chromium 153. I did not test Safari or Firefox, so repeat the checks there.

The service worker lifecycle in 60 seconds

A service worker is a script the browser runs separately from your page, so it can intercept requests. Updates follow a fixed sequence:

  • Detection: your worker counts as updated if it's byte-different from the one the browser already has. An update check is triggered by a navigation to an in-scope page, or by functional events such as push and sync (unless there was a check in the last 24 hours).
  • Install: the new worker installs alongside the old one. If it returns a non-OK status such as a 404, fails to parse, or rejects during install, the new worker is thrown away and the current one stays active.
  • Waiting: once installed, the new worker waits until the existing worker controls zero clients. Clients overlap during a refresh, so a reload does not release it.
  • Activate: the worker activates. self.skipWaiting() skips the waiting step, and clients.claim() takes control of pages that loaded without the worker.
  • Script caching: most browsers, including Chrome 68 and later, ignore HTTP caching headers when checking the registered worker script. Imported scripts still respect them unless you set updateViaCache.

Why the "one version at a time" rule exists: two tabs running different versions of a site can disagree about shared storage, which can cause errors or, worse, data loss.

The lab: two releases and a real browser

To avoid hand-waving, I built a small lab. A build script generates two releases of a tiny app. A static server serves one of them and lets a test "deploy" the next. A Puppeteer test then drives Chromium through the failure and asserts what the user sees.

Two details matter:

  • Every response is Cache-Control: no-cache. Any staleness you see comes from the service worker, not the HTTP cache.
  • The app has a lazy-loaded chunk (feature.v1.js) behind a button, like a route or feature a bundler would split out. Version skew shows up there.

The repo is here: [REPO URL: publish sw-update-lab and insert the link]. Run it with npm install && npm test.

Repro 1: Cache First HTML

The worker precaches the document and serves everything cache-first, including navigations:

self.addEventListener('fetch', (event) => {
  event.respondWith(caches.match(event.request).then((hit) => hit || fetch(event.request)));
});

Steps: load release 1 and reload once so the page is controlled, deploy release 2, then reload.

What I observed:

  • After the deploy, three reloads all still showed release 1.
  • The browser did find the new worker. It installed and sat in the waiting state behind the old one.
  • Another reload did not release it.
  • After closing every tab and opening a fresh one, release 2 appeared.

The new HTML was never fetched, because the old worker answered the navigation from its cache. The user is stuck until the old worker has zero clients, which can take a long time if people keep the app open or resume it from the background. I haven't measured how often real users fully close a PWA, so treat that as a risk, not a rate.

Repro 2: a worker URL that changes every release

Some build setups put a hash in the worker filename and register that URL:

<script>
  navigator.serviceWorker.register('/sw.' + RELEASE + '.js'); // /sw.v1.js, then /sw.v2.js
</script>

Release 2 ships /sw.v2.js and no longer serves /sw.v1.js. With the cached HTML still calling the old registration, nothing tells the browser about the new URL.

What I observed:

TypeError: Failed to update a ServiceWorker for scope ('http://localhost:…/')
with script ('http://localhost:…/sw.v1.js'):
A bad HTTP response code (404) was received when fetching the script.
  • The browser keeps checking the URL it registered. That URL 404s, so the update is discarded and the old worker stays active.
  • There was no waiting worker.
  • Closing every tab did not help. A fresh tab still showed release 1, because the active worker served it from cache.

This one doesn't heal on its own. The fix is to keep a worker at the old URL.

Fix: a rescue worker at the old URL

From release 2 on, serve something at /sw.v1.js that cleans up and sends clients on their way:

// served at the OLD worker URL from release 2 onwards
self.addEventListener('install', () => self.skipWaiting());

self.addEventListener('activate', (event) => {
  event.waitUntil((async () => {
    for (const key of await caches.keys()) await caches.delete(key);
    await self.registration.unregister();
    const windows = await self.clients.matchAll({ type: 'window' });
    windows.forEach((client) => client.navigate(client.url));
  })());
});

What I observed: the stuck client's next update check fetched the rescue worker, which activated, cleared caches, unregistered itself and reloaded the tab. The page came back as release 2 and registered /sw.v2.js.

Then stop changing the worker URL. Register /sw.js every time, and let the byte difference trigger updates.

Repro 3: skipWaiting() under an open tab

skipWaiting() looks like the answer to Repro 1, so many guides add it, together with cache cleanup and clients.claim():

self.addEventListener('install', (event) => {
  self.skipWaiting();
  event.waitUntil(caches.open(CACHE).then((c) => c.addAll(ASSETS)));
});

self.addEventListener('activate', (event) => {
  event.waitUntil(
    caches.keys()
      .then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k))))
      .then(() => self.clients.claim())
  );
});

Steps: keep a release 1 tab open, deploy release 2, let the update check run, then click "Load feature" in the old tab.

What I observed:

FAILED: Failed to fetch dynamically imported module: http://localhost:…/feature.v1.js

The old page is still running release 1 code, but the new worker has deleted release 1's cache, and the server no longer has feature.v1.js. Any lazy route, image or API shape that changed between releases can break the same way. The same version mismatch can also hit shared storage.

A note on timing. My first version of this test passed by accident. It clicked while the new worker was still activating, and the release 1 cache still existed. I fixed the test to wait for activation. Version skew bugs are timing-dependent, so "it worked when I tried it" proves little.

Safe patterns for a service worker update strategy

Failure, Causes and Fix Table

1. Network First for navigations, Cache First for versioned assets

if (request.mode === 'navigate') {
  event.respondWith((async () => {
    try {
      return await fetch(request);                       // always try the network for the HTML
    } catch {
      const cache = await caches.open(CACHE);            // this release's cache, explicitly
      return (await cache.match('/index.html')) || Response.error();
    }
  })());
  return;
}
// Hashed asset URLs never change content, so Cache First is safe here.
event.respondWith(caches.match(request).then((hit) => hit || fetch(request)));

Open the current cache by name for the fallback. caches.match() searches every cache, in creation order, so an older cache can answer first. In production, consider a network timeout (Workbox's NetworkFirst has networkTimeoutSeconds), because plain Network First waits for a failing connection.

2. Prompt, then skipWaiting(), then reload

Let the page detect the waiting worker and ask. Chrome's Workbox docs describe this as waiting event, user accepts, messageSkipWaiting(), reload on controlling. In plain code:

// page
const reg = await navigator.serviceWorker.register('/sw.js', { updateViaCache: 'none' });
const prompt = () => { if (reg.waiting && navigator.serviceWorker.controller) showUpdateButton(); };
prompt();
reg.addEventListener('updatefound', () => reg.installing.addEventListener('statechange', prompt));

updateButton.onclick = () => { accepted = true; reg.waiting.postMessage({ type: 'SKIP_WAITING' }); };
navigator.serviceWorker.addEventListener('controllerchange', () => { if (accepted) location.reload(); });

// service worker
self.addEventListener('message', (e) => { if (e.data?.type === 'SKIP_WAITING') self.skipWaiting(); });

If you use Workbox's generateSW with skipWaiting left at its default of false, the message listener is included for you. The Workbox docs also say a prompt makes the most sense when you precache heavily or serve precached HTML.

What I observed: after a deploy, the page showed the update prompt and stayed on release 1 with a working lazy chunk. After accepting, the page reloaded into release 2.

3. Keep the previous release's cache

Delete only caches older than the previous release:

for (const key of await caches.keys()) {
  const n = Number(key.replace('app-v', ''));
  if (Number.isFinite(n) && n < N - 1) await caches.delete(key);
}

What I observed: with a second tab still on release 1, accepting the update in the first tab activated the new worker. The second tab's "Load feature" click still returned feature v1 ok, served from the retained cache.

4. Practices I did not test in the lab

These are standard practice, but the lab doesn't cover them:

  • Keep old hashed assets on the server for a release or two, so open tabs can still fetch them.
  • Call registration.update() when the app becomes visible. Update checks are triggered by navigations and functional events, and a long-lived single-page app may not navigate for days.
  • Catch lazy-chunk load errors in the app and offer a reload, rather than leaving a blank screen.

Testing updates locally and in CI

The test pattern is the same for every scenario:

await installAndControl(page);          // register, wait for 'ready', reload so the page is controlled
assert.equal(await version(page), 'v1');

lab.deploy(2);                          // release 2 is now live
await checkForUpdate(page);             // registration.update()

assert.equal(await version(page), 'v1');   // still release 1 until the update is applied

Four lessons from writing these tests:

  • Wait for states, not time. Wait for reg.waiting, or for reg.active.state === 'activated', before asserting.
  • A reload does not release a waiting worker. Closing all clients does, which is why Repro 1 needs a second page.
  • Use a fresh browser per test. Each run needs its own service worker storage.
  • Keep DevTools' "Update on reload" off when you want to see what users see, because it forces an update check on every load.

In CI, install a Chrome binary and point the tests at it with CHROME_PATH (and NO_SANDBOX=1 in containers).

Checklist for reviewers

  1. The worker is registered at one stable URL (/sw.js), not a per-release filename.
  2. HTML navigations are Network First or otherwise revalidated, never plain Cache First.
  3. Cache First is used only for assets with content-hashed URLs.
  4. skipWaiting() runs on user consent, not unconditionally in install.
  5. The page reloads only after controllerchange that follows an accepted update.
  6. Cache cleanup keeps the previous release for open tabs.
  7. The offline navigation fallback reads the active release's cache, not the first match.
  8. Old hashed assets stay on the server for at least one release.
  9. Long-lived sessions call registration.update() on a sensible trigger.
  10. A two-release test exists, and runs in CI, with a waiting-worker assertion.
  11. A rescue worker exists if you ever shipped a per-release worker URL.

Conclusion

Update bugs come from the combination: cached HTML, worker versioning and which assets still exist after a deploy. Test with two releases, wait for lifecycle states, and let the user choose when to switch.

If you're hiring for PWA work, update behavior is one of the first things worth probing. See what to ask a candidate about updates in our complete guide to hiring PWA developers.

πŸ“° Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.