Hi folks,
Welcome again! I hope you are doing well. I am thrilled to see you here. So today, we will discuss about Angular Service Worker.
Introduction
In today’s fast-paced web environment, users expect applications to load instantly, work offline, and provide a seamless experience even on flaky networks. Angular offers a powerful built-in solution to help you meet these expectations: the Angular Service Worker.
What is a Service Worker?
A service worker is a special script that runs in the background of a web browser.
It acts as a proxy between your application and the network, allowing you to intercept and manage network requests, cache resources, and deliver a reliable user experience even when the internet connection is poor or non-existent.
Why Use Service Workers in Angular?
Angular provides first-class support for service workers, tightly integrated into the Angular CLI and ecosystem.
Below are some compelling reasons to use them:
- Offline Support: Users can still access key features and content when disconnected.
- Performance Boost: The service worker caches resources locally to reduce load times.
- Automatic Updates: Angular handles update checks and version management.
- Push Notifications: Optional integration for user re-engagement.
Angular’s Native Support for Service Workers
Angular includes a dedicated package, @angular/service-worker, which simplifies the setup and management of service workers in your Angular projects.
The configuration is done using a declarative JSON file, making the process approachable for most developers.
Setting Up Service Workers in Angular
To enable service workers, follow the below steps:
1) Install the Package
Ensure your project includes @angular/pwa by running:
ng add @angular/pwa
This automatically install the package and configures your app as a Progressive Web App.
2) Update angular.json
The CLI modifies your build settings to include the service worker script in the production build.
3) Configure ngsw-config.json
This file controls how resources are cached. For example:
{
"index": "/index.html",
"assetGroups": [
{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [
"/favicon.ico",
"/index.html",
"/*.css",
"/*.js"
]
}
},
{
"name": "images",
"installMode": "lazy",
"updateMode": "prefetch",
"resources": {
"files": [
"/assets/images/**"
]
}
}
],
// FOR API Calls
"dataGroups": [
{
"name": "api-calls",
"urls": [
"https://api.example.com/**"
],
"cacheConfig": {
"maxSize": 50,
"maxAge": "1h",
"timeout": "10s",
"strategy": "performance"
}
},
{
"name": "user-data",
"urls": [
"https://api.example.com/users/**"
],
"cacheConfig": {
"maxSize": 20,
"maxAge": "10m",
"timeout": "5s",
"strategy": "freshness"
}
}
]
}
4) Setting Up Groups Configurations
- Asset Groups: Define how local resources like JS, CSS, images are cached.
installMode:prefetch(download all at once) orlazy(on first request).updateMode: Controls how updates are applied (prefetchorlazy).
- Data Groups: Define caching for external requests like APIs.
urls: Match external request URLs.cacheConfig: Customize cache size, expiration, timeout, and fetch strategy.strategy:performance: Serve cached data first and refresh in background.freshness: Try network first, fallback to cache if offline.
5) Build and Deploy:
ng build --prod
Then serve the files over HTTPS.
How Angular Service Workers Work
Angular service workers follow a lifecycle
- Installation: The browser registers the worker script and caches it.
- Activation: The service worker clears old caches and activates new ones.
- Fetch Interception: The service worker intercepts requests and serves cached responses or fetches from the network.
The configuration allows strategies like prefetching all files or lazy loading Service Workers only what’s needed.
Practical Use Cases
- Static Asset Caching: Cache stylesheets, JavaScript, and images for quick access.
- App Shell Model: Load minimal UI instantly while dynamic content loads.
- Background Data Sync: Keep app data fresh when connectivity resumes.
- Push Notifications: Engage users with timely alerts.
Debugging and Testing
Use Chrome DevTools:
- Go to
Application > Service Workers - Inspect and unregister workers as needed
- Use
ng build --prodto simulate a realistic environment
Security Considerations
- Service workers only work on HTTPS domains (except
localhost). - Be cautious with caching dynamic content to prevent outdated data.
Local Development Options for Service Workers
Use localhost (No HTTPS Required)
Angular CLI supports service workers on localhost during development builds using production flags.
ng build --configuration production
npx http-server -p 8080 -c-1 dist/your-app-name
http-server is a Node.js package to serve static files.
The -c-1 disables cache for easier debugging.
Then visit: http://localhost:8080
Conclusion
Service workers bring the power of offline capability, caching, and enhanced performance to Angular apps. With Angular’s CLI tooling and configuration model, integrating a service worker is straightforward and scalable.
Empower your users with reliability, speed, and offline access – all with just a few lines of configuration.
Hey, let’s stay in touch!
If you liked this blog, please share it with your friends and colleagues. Connect with FE competency on LinkedIn to read more about such topics.