← Back to Angular, page 7

angular-0139 · Hard senior

Write a service that checks for service worker updates, prompts the user when a new version is ready, and recovers from an unrecoverable state.

Inject SwUpdate, listen to versionUpdates for VERSION_READY and show a prompt, call checkForUpdate on a timer for long lived tabs, reload after the user accepts (activateUpdate then location.reload), and handle unrecoverable events by reloading, because the cached files no longer match.

Full answer

The service worker downloads a new version in the background but keeps serving the old one until the page is reloaded. A good update service completes the loop.

Parts:

  1. SwUpdate.isEnabled: false in development and in browsers without support. Guard everything with it.
  2. versionUpdates: an observable of events: VERSION_DETECTED (a new version started downloading), VERSION_READY (downloaded, ready to activate), VERSION_INSTALLATION_FAILED, and NO_NEW_VERSION_DETECTED. Filter for VERSION_READY and set a signal updateReady that the UI shows as "A new version is available".
  3. Accept: await swUpdate.activateUpdate() then document.location.reload(). Activating without reload would give new files to an old page, which can break lazy chunk loads.
  4. Periodic checks: the worker checks on start. A tab left open for days needs checkForUpdate() on a timer, for example every 6 hours, or when the tab becomes visible again. Run the timer outside Angular's zone, or with interval and takeUntilDestroyed, and avoid timers that keep the app unstable, which would delay the registerWhenStable strategy (use afterNextRender or start after ApplicationRef.isStable).
  5. unrecoverable: an event that tells you the worker's cache is corrupt or files went missing. The page can no longer trust cached assets, so inform the user and reload.

Design notes:

  • Do not force a reload without warning, since the user may lose form input. Prompt, and let the user choose, or reload on a safe navigation.
  • For critical fixes, a version check API (a small JSON file with the minimum version) can force the prompt.
  • Test with a production build served over localhost, change a file, rebuild, and watch the update flow in the browser's Application tab.
  • Log events to monitoring, to see how many users run old versions.
typescript
import { DestroyRef, Injectable, inject, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { SwUpdate, VersionReadyEvent } from '@angular/service-worker';
import { filter, interval } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class AppUpdateService {
  private readonly sw = inject(SwUpdate);
  private readonly destroyRef = inject(DestroyRef);

  readonly updateReady = signal(false);
  readonly broken = signal(false);

  constructor() {
    if (!this.sw.isEnabled) {
      return;
    }

    this.sw.versionUpdates
      .pipe(
        filter((e): e is VersionReadyEvent => e.type === 'VERSION_READY'),
        takeUntilDestroyed(this.destroyRef),
      )
      .subscribe(() => this.updateReady.set(true));

    this.sw.unrecoverable.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => this.broken.set(true));

    interval(6 * 60 * 60 * 1000)
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe(() => void this.sw.checkForUpdate());
  }

  async applyUpdate(): Promise<void> {
    await this.sw.activateUpdate();
    document.location.reload();
  }
}

Angular 20.3 with `@angular/service-worker` 20.3, type-checked. It was not run in a browser here, because that needs a production build served over HTTP with a real service worker.

Key points

  • Guard with `SwUpdate.isEnabled`. Listen to `versionUpdates` for `VERSION_READY`.
  • Prompt, then `activateUpdate()` and reload. Do not activate without reloading.
  • Check periodically for long lived tabs. Handle `unrecoverable`.
  • Avoid surprise reloads. Test with a production build.

Common mistakes

  • Activating an update without reloading the page.
  • Starting an endless timer that stops the app from becoming stable.
  • Forcing a reload and losing the user's input.

Follow-ups

  • What does `registerWhenStable` do and how can a timer break it?
  • How would you require a minimum version?
  • How would you test the update flow?

Tips

  • Name the event types.
  • Mention the lost input problem.
  • Say you log update events.

Evaluation rubric

  • Uses SwUpdate events correctly.
  • Implements prompt, activation and reload.
  • Handles unrecoverable state and periodic checks.