Angular has its own service worker, configured with JSON rather than code.
Add it
ng add @angular/pwa
This adds manifest.webmanifest, default icons, ngsw-config.json, links the manifest in index.html, and registers the worker in your app config:
provideServiceWorker('ngsw-worker.js', {
enabled: !isDevMode(),
registrationStrategy: 'registerWhenStable:30000',
})
The worker only runs in production builds (ng build), so test with a static server on dist/.
ngsw-config.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": "api-fresh", "urls": ["/api/feed/**"], "cacheConfig": { "strategy": "freshness", "maxSize": 50, "maxAge": "1d", "timeout": "4s" } },
{ "name": "api-fast", "urls": ["/api/catalog/**"], "cacheConfig": { "strategy": "performance", "maxSize": 100, "maxAge": "7d" } }
]
}
- assetGroups: your build files.
prefetchdownloads at install;lazyon first use. - dataGroups: API responses.
freshnessis network-first with a timeout;performanceis cache-first.
Updates with SwUpdate
const updates = inject(SwUpdate);
updates.versionUpdates
.pipe(filter((e): e is VersionReadyEvent => e.type === 'VERSION_READY'))
.subscribe(() => {
if (confirm('A new version is available. Load it?')) document.location.reload();
});
Call updates.checkForUpdate() on an interval or when the tab becomes visible. SwPush handles web push subscriptions and notification clicks.