← Back to Angular, page 7

angular-0133 · Medium mid

How does the Angular service worker (ngsw) work, how do you configure caching, and how do you handle app updates?

The Angular service worker is a script that sits between the app and the network and caches the app shell, assets and chosen API responses according to ngsw-config.json. It checks for a new version in the background, and the app can ask users to reload with SwUpdate. It only works over HTTPS and in production builds.

Full answer

A service worker is a script the browser runs in the background, separate from the page. It can intercept network requests, so it can answer from a cache when the network is slow or missing. Angular provides @angular/service-worker, added with ng add @angular/pwa, which also adds a web app manifest and icons.

Set-up:

  • provideServiceWorker('ngsw-worker.js', { enabled: !isDevMode(), registrationStrategy: 'registerWhenStable:30000' }) in the app config.
  • ngsw-config.json describes caching. assetGroups cache the app files: app (the shell, prefetch) and assets (images and fonts, lazy). dataGroups cache API calls with a strategy: freshness (network first, fall back to cache after a timeout) or performance (cache first, refresh after maxAge), plus maxSize and maxAge.
  • The build produces ngsw.json, a manifest with hashes of every file. The worker uses it to know exactly what version it has.

Update flow:

  1. On start the worker fetches ngsw.json in the background.
  2. If the hashes changed, it downloads the new files into a new version, but keeps serving the old version to open tabs, so the page never mixes files from two versions.
  3. The app can listen to SwUpdate.versionUpdates for a VERSION_READY event and show "A new version is available. Reload". Then document.location.reload() or swUpdate.activateUpdate() followed by a reload switches to the new version.
  4. For long-lived tabs, call swUpdate.checkForUpdate() on a timer.

Cautions:

  • It works only on HTTPS (or localhost) and does nothing with ng serve. Test with a production build served by a static server.
  • Cached index.html can keep users on an old version, so always give an update prompt.
  • Never cache authenticated API responses that differ per user without care, and clear caches on logout (caches API).
  • A broken service worker is hard to remove. Keep the "safety worker" (safety-worker.js) in mind and test updates.
  • Do not cache everything. A large cache costs storage and can show stale data.
typescript
// file: 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',
    }),
  ],
};

// file: ngsw-config.json
{
  "$schema": "./node_modules/@angular/service-worker/config/schema.json",
  "index": "/index.html",
  "assetGroups": [
    { "name": "app", "installMode": "prefetch", "resources": { "files": ["/favicon.ico", "/index.html", "/*.css", "/*.js"] } },
    { "name": "assets", "installMode": "lazy", "updateMode": "prefetch", "resources": { "files": ["/assets/**", "/*.(svg|png|webp|woff2)"] } }
  ],
  "dataGroups": [
    { "name": "courses-api", "urls": ["/api/courses/**"], "cacheConfig": { "strategy": "freshness", "maxSize": 50, "maxAge": "1h", "timeout": "3s" } }
  ]
}

Angular 20.3 with `@angular/service-worker` 20.3, type-checked. The config files are examples and were not run in a browser here, so offline behaviour was not tested.

Key points

  • The service worker intercepts requests and serves from cache, using `ngsw-config.json` rules and the generated `ngsw.json` manifest.
  • `assetGroups` for files, `dataGroups` for API calls (freshness or performance).
  • Updates download in the background. `SwUpdate` lets the app prompt a reload.
  • Needs HTTPS and a production build. Be careful with user-specific data in caches.

Common mistakes

  • Testing the service worker with `ng serve` and finding nothing happens.
  • Not showing an update prompt, so users stay on an old version.
  • Caching user-specific API data without clearing it on logout.

Follow-ups

  • What is the difference between `freshness` and `performance` strategies?
  • How does the worker avoid mixing files from two versions?
  • How would you test offline behaviour?

Tips

  • Describe the update flow step by step. It is the usual question.
  • Mention HTTPS and production only.
  • Mention privacy of cached data.

Evaluation rubric

  • Explains how the worker and ngsw.json work.
  • Knows configuration groups and strategies.
  • Handles updates and risks.