Date: March 10, 2024
In today’s mobile-first world, building web apps that work seamlessly offline is more than a nice-to-have — it’s often essential. Angular provides powerful Progressive Web App (PWA) features, including Service Workers, which enable your app to cache resources, serve fallback content, and deliver smooth user experiences even without network connectivity.
This tutorial walks you through how to build an offline-first Angular app using Angular’s built-in PWA support, configuring service workers, and implementing smart caching strategies and fallbacks.
What Is a Service Worker?
A Service Worker is a background script that intercepts network requests made by your web app. It can:
- Cache files locally
- Serve cached content when offline
- Handle background sync and push notifications
Angular makes integrating service workers straightforward via the @angular/pwa
package.
Step 1: Adding PWA Support to Your Angular App
Start by adding PWA capabilities using Angular CLI:
ng add @angular/pwa
This command:
- Adds and configures
@angular/service-worker
- Creates a
ngsw-config.json
file for caching strategies - Adds necessary meta tags and manifest files
Step 2: Understanding ngsw-config.json
The ngsw-config.json
file defines caching behavior for assets and data requests.
Here’s an example configuration:
{
"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/**"]
}
}
],
"dataGroups": [
{
"name": "api-freshness",
"urls": ["/api/**"],
"cacheConfig": {
"strategy": "freshness",
"maxSize": 100,
"maxAge": "1h",
"timeout": "5s"
}
}
]
}
- assetGroups control static resource caching:
prefetch
downloads assets during installation.lazy
caches on demand.- dataGroups manage dynamic data caching:
"strategy": "freshness"
prefers network but falls back to cache."strategy": "performance"
favors cache first.
Step 3: Registering the Service Worker in Your App
Angular CLI automatically registers the service worker in production builds, but here’s what happens under the hood in main.ts
:
if ('serviceWorker' in navigator && environment.production) {
navigator.serviceWorker.register('/ngsw-worker.js').then(() => {
console.log('Service Worker Registered');
});
}
Ensure you build your app with:
ng build --prod
Step 4: Implementing Offline Fallback Strategies
Sometimes network requests fail. You can customize fallbacks for offline use, such as:
- Serving cached API responses
- Displaying a custom offline page
- Queueing failed requests for retry later
For example, to show a simple offline page, add to your index.html
:
<noscript>
<p>You are offline. Please check your internet connection.</p>
</noscript>
Step 5: Testing Your Offline App
Use Chrome DevTools to simulate offline mode:
- Open DevTools (F12)
- Go to Network tab
- Check Offline checkbox
- Refresh the page — your cached content should load smoothly!
Step 6: Advanced Tips
- Use Background Sync API to retry failed requests automatically when back online.
- Customize caching by adding more URL patterns in
dataGroups
. - Use Workbox or custom service workers if you need more control beyond Angular’s defaults.
Example: Caching API Data with Freshness Strategy
Imagine a news app fetching articles from /api/articles
.
In ngsw-config.json
:
{
"dataGroups": [
{
"name": "articles-api",
"urls": ["/api/articles/**"],
"cacheConfig": {
"strategy": "freshness",
"maxSize": 50,
"maxAge": "30m",
"timeout": "5s"
}
}
]
}
- The service worker tries network first but falls back to cache after 5 seconds.
- Cached responses are retained for 30 minutes and max 50 entries.
Summary
Using Angular’s PWA features and service workers lets you build offline-first apps that:
- Improve load performance
- Work reliably in flaky networks
- Provide smooth UX with cached assets and data
Start integrating service workers today to future-proof your Angular apps for real-world usage.