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.jsondescribes caching.assetGroupscache the app files:app(the shell,prefetch) andassets(images and fonts,lazy).dataGroupscache API calls with a strategy:freshness(network first, fall back to cache after a timeout) orperformance(cache first, refresh aftermaxAge), plusmaxSizeandmaxAge.- 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:
- On start the worker fetches
ngsw.jsonin the background. - 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.
- The app can listen to
SwUpdate.versionUpdatesfor aVERSION_READYevent and show "A new version is available. Reload". Thendocument.location.reload()orswUpdate.activateUpdate()followed by a reload switches to the new version. - 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.htmlcan 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 (
cachesAPI). - 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.