Skip to content
Tutorials Center
My learning

Topics

Lesson 51 of 74 ยท Quality and Performance

PWAs and Service Workers

Turn an Angular app into a Progressive Web App with ng add @angular/pwa. Learn ngsw-config caching groups, offline behavior and SwUpdate, with runnable cache-strategy stand-ins.

A Progressive Web App (PWA) is a normal web app that can also behave like an installed app: it starts quickly, keeps working with a bad connection or none at all, and can be added to the home screen. The technology behind this is the service worker, a script that the browser runs in the background, between your page and the network.

Angular ships a ready-made service worker and a small library around it. In this lesson you will add it, configure what it caches, handle updates with SwUpdate, and understand the caching strategies well enough to avoid the classic "users are stuck on the old version" trap.

Real versus stand-in. A service worker needs a browser, HTTPS (or localhost) and a production build, and the sandbox that runs our examples forbids service workers. So the bash, json and typescript blocks are real code to read, and the runnable examples are stand-ins: they model the caching strategies and the update check in plain TypeScript with a fake network and a fake cache.

What a service worker does

A service worker sits between the page and the network and can answer a request from its own cache instead.

flowchart LR
  P["Page<br/>(your Angular app)"] -->|request| S["Service worker"]
  S -->|cache hit| C[("Cache storage")]
  S -->|cache miss or refresh| N["Network"]
  N -->|response| S
  S -->|response| P

The page never knows whether the answer came from the cache or the network.

Three facts to remember. It runs on its own thread with no access to the DOM. It only works over HTTPS (localhost counts as secure for development). And it is registered once and then lives on after the tab closes, which is powerful and the reason updates need care.

Adding the Angular service worker

One command does the setup:

Terminal
ng add @angular/pwa

It installs @angular/service-worker, adds a web app manifest and icons, links the manifest in index.html, creates ngsw-config.json and registers the worker. The registration lives in your application config:

TypeScript
// app.config.ts
import { ApplicationConfig, isDevMode } from '@angular/core';
import { provideServiceWorker } from '@angular/service-worker';

export const appConfig: ApplicationConfig = {
  providers: [
    provideServiceWorker('ngsw-worker.js', {
      enabled: !isDevMode(),
      registrationStrategy: 'registerWhenStable:30000',
    }),
  ],
};

enabled: !isDevMode() keeps the worker off during ng serve, so you never debug stale caches by accident. registerWhenStable:30000 waits until the app is stable (or 30 seconds) before registering, so the worker does not compete with your first load. To test it, build and serve the production output with a static server:

Terminal
ng build
npx http-server -p 8080 -c-1 dist/my-app/browser

Open the page, then look at Application > Service Workers in the browser developer tools. Tick "Offline" and reload: the app should still start.

ngsw-config.json: what to cache

You do not write the worker. You describe, in ngsw-config.json, which files and which API calls it should cache:

JSON
{
  "$schema": "./node_modules/@angular/service-worker/config/schema.json",
  "index": "/index.html",
  "assetGroups": [
    {
      "name": "app",
      "installMode": "prefetch",
      "resources": { "files": ["/favicon.ico", "/index.csr.html", "/index.html", "/manifest.webmanifest", "/*.css", "/*.js"] }
    },
    {
      "name": "assets",
      "installMode": "lazy",
      "updateMode": "prefetch",
      "resources": { "files": ["/**/*.(svg|cur|jpg|jpeg|png|webp|avif|gif|otf|ttf|woff|woff2)"] }
    }
  ],
  "dataGroups": [
    {
      "name": "api-forecast",
      "urls": ["/api/forecast/**"],
      "cacheConfig": {
        "strategy": "freshness",
        "maxSize": 50,
        "maxAge": "1h",
        "timeout": "5s"
      }
    }
  ]
}

There are two kinds of groups.

  • Asset groups are your app's own files, versioned together with the build. installMode: "prefetch" downloads everything immediately; "lazy" caches a file when it is first requested. updateMode says how files already cached are refreshed when a new version arrives.
  • Data groups are API responses, which are not versioned with the app. Here you choose a strategy:
    • freshness: try the network first, fall back to the cache if the network is slower than timeout or fails. Use it for data that should be current, such as a forecast or an account balance.
    • performance: answer from the cache while it is younger than maxAge, otherwise go to the network. Use it for data that changes rarely, such as a list of countries.

Never cache responses that contain private user data unless you understand the consequences: the cache lives on the user's device. Requests with credentials and POST requests are not cached by Angular's worker.

Two strategies, modeled

Here is a model of the two strategies with a fake network that can go offline. It shows when each one serves cached data.

TypeScript freshness versus performance caching

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Keeping users up to date with SwUpdate

Here is the trap. When you deploy a new version, the worker that is already installed keeps serving the old files from its cache. The new version downloads in the background and becomes active only on a later load. So a user who never closes the tab can run last month's code. SwUpdate lets you handle this on purpose:

TypeScript
import { ApplicationRef, inject, Injectable } from '@angular/core';
import { SwUpdate, VersionReadyEvent } from '@angular/service-worker';
import { filter, first, interval, concat } from 'rxjs';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';

@Injectable({ providedIn: 'root' })
export class UpdateService {
  private readonly updates = inject(SwUpdate);
  private readonly appRef = inject(ApplicationRef);

  start(): void {
    if (!this.updates.isEnabled) return;

    // Check for a new version every 6 hours, once the app is stable
    const stable$ = this.appRef.isStable.pipe(first(isStable => isStable));
    concat(stable$, interval(6 * 60 * 60 * 1000))
      .pipe(takeUntilDestroyed())
      .subscribe(() => this.updates.checkForUpdate());

    this.updates.versionUpdates
      .pipe(filter((event): event is VersionReadyEvent => event.type === 'VERSION_READY'))
      .subscribe(() => {
        if (confirm('A new version is available. Reload now?')) {
          document.location.reload();
        }
      });

    this.updates.unrecoverable.subscribe(event => {
      alert(`The app must reload: ${event.reason}`);
      document.location.reload();
    });
  }
}

checkForUpdate() asks the server whether a new build exists, versionUpdates reports when it is ready, and unrecoverable fires when the cache is broken and a reload is the only fix. In a real product use a friendly banner instead of confirm(), and never reload in the middle of a form without asking: users lose their work.

The check works by comparing a manifest: the worker downloads ngsw.json, which lists every file with a hash. If the hashes differ from the installed version, a new version exists. This stand-in does the same comparison.

TypeScript Detecting a new version by comparing hashes

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Only files whose hash changed are downloaded, which is why updates are cheap.

The web app manifest and installability

manifest.webmanifest (created by ng add @angular/pwa) tells the browser how to show the app when installed:

JSON
{
  "name": "Weather Dashboard",
  "short_name": "Weather",
  "display": "standalone",
  "start_url": "/",
  "theme_color": "#1976d2",
  "background_color": "#fafafa",
  "icons": [
    { "src": "icons/icon-192x192.png", "sizes": "192x192", "type": "image/png" },
    { "src": "icons/icon-512x512.png", "sizes": "512x512", "type": "image/png" }
  ]
}

With a valid manifest, a registered worker and HTTPS, browsers offer an install button. Run Lighthouse (in the browser dev tools) and check the PWA and performance reports to see what is missing.

Common mistakes

  • Testing in ng serve. The worker is disabled in development; always test with a production build.
  • Caching index.html forever by hand in a CDN or with HTTP headers. Serve ngsw.json and ngsw-worker.js with Cache-Control: no-cache, or updates will not be noticed.
  • Cache-first for API data that should be current. Use freshness for anything users expect to be live.
  • No update flow. If you do not use SwUpdate, users may run old code for days.
  • Forgetting to unregister during a bug hunt. In the developer tools, use "Unregister" and "Clear site data" before concluding that your code is wrong.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where does a service worker sit?

    It runs on its own thread in the browser and can answer requests itself. The page cannot tell where the answer came from.
  2. 2. Which dataGroup strategy tries the network first and falls back to the cache?

    freshness prefers current data and uses the cache when the network fails or times out. performance prefers the cache while it is young.
  3. 3. Why do users sometimes run an old version after a deploy?

    The new version downloads in the background but becomes active later. SwUpdate lets you detect it and ask the user to reload.
  4. 4. Why should the service worker be disabled in development mode?

    With the worker on, you may keep seeing cached files after editing code. Enabling it only in production builds avoids that confusion.

Summary

  • A service worker is a background script between the page and the network; it needs HTTPS or localhost.
  • ng add @angular/pwa adds the worker, the manifest, icons and ngsw-config.json; provideServiceWorker registers it.
  • Asset groups cache your build files; data groups cache API responses with a freshness or performance strategy.
  • Use SwUpdate to check for updates, detect VERSION_READY and ask the user to reload.
  • Test with a production build, serve the worker and manifest with no-cache headers and never cache private data carelessly.
  • The configuration and Angular code are real and read-only here; the runnable examples are stand-ins for the strategies and the update check.

Next: Web Workers in Angular