How to add service worker in Angular
Adding service workers enables Angular applications to cache assets, work offline, and provide faster load times for returning users. As the creator of CoreUI with over 11 years of Angular development experience since 2014, I’ve implemented service workers in numerous enterprise applications. The most effective solution is to use Angular’s built-in service worker package which handles caching and updates automatically. This approach requires minimal configuration and provides robust offline capabilities.
Add Angular Service Worker using Angular CLI commands.
# Add service worker to existing project
ng add @angular/pwa
# This command automatically:
# - Installs @angular/service-worker package
# - Adds ngsw-config.json configuration
# - Updates angular.json
# - Adds service worker registration to app.module.ts
# - Creates manifest.webmanifest
# - Adds icons
# Build for production (service worker only works in production)
ng build --configuration production
# Serve production build locally to test
npx http-server -p 8080 -c-1 dist/your-app
// 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/**",
"/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)"
]
}
}
],
"dataGroups": [
{
"name": "api",
"urls": ["/api/**"],
"cacheConfig": {
"maxSize": 100,
"maxAge": "1h",
"strategy": "freshness"
}
}
]
}
The ng add @angular/pwa command sets up everything needed for a Progressive Web App. Asset groups define which files to cache and when. The app group prefetches critical files, while assets are loaded lazily. Data groups configure API response caching with strategies like freshness (network first) or performance (cache first).
Best Practice Note
This is the same service worker configuration we use in CoreUI Angular applications for offline capability. Service workers only work over HTTPS in production and localhost in development. Test thoroughly as caching can make debugging difficult - use Chrome DevTools Application tab to inspect and clear service worker cache during development.



