Planning an Angular PWA Guide
The user is asking for guidance on building an Angular PWA with service workers and advanced caching strategies. I’ll assume they’re referencing Angular 17 or later. I should explore Angular's PWA support, including installation and service worker configuration. I want to cover caching strategies like performance vs. freshness, route-based caching, and API caching. I'll mention using Workbox for advanced strategies if needed, while keeping examples, commands, and code snippets clear for implementation. Let's make this easy to follow!Structuring Angular PWA Information
I want to create a concise yet informative guide for building a PWA with Angular, ideally suited for Angular 18 since it’s 2025. I’ll start with creating the project using ng new pwa-demo --routing --style=scss, and then add PWA support with ng add @angular/pwa. Including a sample ngsw-config.json will be crucial, outlining assetGroups and advanced caching strategies. I’ll ensure to touch on manifest.json, icons, and meta tags, plus testing recommendations with Lighthouse. A modern Angular focus will keep it relevant.Focusing on Advanced Caching Strategies
For the user's request on advanced caching strategies, I’ll concentrate on Angular's configuration-level features rather than push notifications or background sync. First, I'll outline key prerequisites before guiding them through creating the Angular project with the CLI and adding PWA support. I want to detail the modifications in main files like manifest.webmanifest and ngsw-config. I'll explain cache strategies by splitting assets and setting up dataGroups for various APIs, along with customizing fallback routes for offline functionality. Let's make sure it's comprehensive yet digestible!Creating a Step-by-Step Guide for Angular PWA
I need to clarify that Angular's Service Worker (SW) doesn’t allow for easy customization of navigation fallback content, as it defaults to serving index.html. However, I can embed an offline UI. I want to show how to enable environment-specific settings using ServiceWorkerModule.register('ngsw-worker.js', {enabled: !isDevMode()}). It's important to cover offline development/testing tips, like using Chrome DevTools.
Also, I might include concepts like runtime caching and how Angular's caching strategies work. I should aim to provide code snippets that users can easily paste, ultimately crafting a skeleton app guide. Let’s start with, “Here’s a step-by-step guide to building an Angular PWA with service workers and advanced caching strategies, using the Angular CLI and Angular Service Worker.”Crafting a Detailed Angular PWA Setup
To set up an Angular PWA, I’ll provide the following commands:
npm install -g @angular/cli
ng new angular-pwa-demo --routing --style=scss
cd angular-pwa-demo
ng add @angular/pwa
Next, I’ll focus on the ngsw-config.json, showcasing how to configure assetGroups for app and assets, along with dataGroups for caching critical APIs. I want to include an explanation of how to enable the service worker in AppModule, confirming isDevMode() usage.
Additionally, I’ll introduce the creation of a simple service, PostsService, for API calls while ensuring proper caching. A minor mention of caching headers like Cache-Control might also be useful. I intend to outline the advanced options related to versioning and updates using SwUpdate, but I should keep the primary focus on caching strategies for clarity. I'll format everything in structured sections to enhance readability. Below is a concrete, end-to-end way to build an Angular PWA with service workers and non‑trivial caching strategies using the built‑in Angular Service Worker.
1. Create the Angular app and add PWA support
# 1. Create a new Angular app
ng new angular-pwa-demo --routing --style=scss
cd angular-pwa-demo
# 2. Add Angular PWA support (service worker, manifest, icons)
ng add @angular/pwa
ng add @angular/pwa will:
- Install
@angular/service-worker
- Add
ServiceWorkerModule to your AppModule
- Create
ngsw-config.json
- Create/modify
manifest.webmanifest
- Add PWA meta tags to
index.html
2. Ensure the service worker is registered correctly
Angular CLI will add something similar to app.module.ts (or your root module if using standalone APIs, adjust accordingly):
import { NgModule, isDevMode } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ServiceWorkerModule } from '@angular/service-worker';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
AppRoutingModule,
ServiceWorkerModule.register('ngsw-worker.js', {
enabled: !isDevMode(), // only enable in production builds
registrationStrategy: 'registerWhenStable:30000',
}),
],
bootstrap: [AppComponent],
})
export class AppModule {}
registrationStrategy: 'registerWhenStable:30000' = register when the app is stable, or after 30s, whichever comes first.
3. Understand the core config: ngsw-config.json
This is where you define caching strategies. A good starting point (edit ngsw-config.json in the project root):
{
"$schema": "./node_modules/@angular/service-worker/config/schema.json",
"index": "/index.html",
"assetGroups": [
{
"name": "app-shell",
"installMode": "prefetch",
"updateMode": "prefetch",
"resources": {
"files": [
"/index.html",
"/*.css",
"/*.js",
"/favicon.ico"
]
}
},
{
"name": "static-assets",
"installMode": "lazy",
"updateMode": "prefetch",
"resources": {
"files": [
"/assets/**",
"/*.(png|jpg|jpeg|svg|webp)"
]
}
}
],
"dataGroups": [
{
"name": "api-critical-fresh",
"urls": [
"https://api.example.com/v1/critical/**"
],
"cacheConfig": {
"maxSize": 50,
"maxAge": "1h",
"timeout": "5s",
"strategy": "freshness"
}
},
{
"name": "api-noncritical-performance",
"urls": [
"https://api.example.com/v1/noncritical/**"
],
"cacheConfig": {
"maxSize": 100,
"maxAge": "7d",
"strategy": "performance"
}
},
{
"name": "cdn-images",
"urls": [
"https://cdn.example.com/images/**"
],
"cacheConfig": {
"maxSize": 200,
"maxAge": "30d",
"strategy": "performance"
}
}
]
}
Asset groups (app shell / static assets)
assetGroups cache compiled JS, CSS, HTML, and other static assets.
installMode:
prefetch: cache everything on first load (good for app shell).
lazy: cache when first requested (good for large images, etc.).
updateMode:
prefetch: eagerly download updated assets in the background.
lazy: update only when requested.
Typical pattern:
- App shell (JS/CSS/HTML) →
prefetch for fast subsequent loads.
- Large assets (images, PDFs) →
lazy to avoid huge initial install.
Data groups (API / dynamic data)
dataGroups are where you get “advanced” runtime caching:
strategy: "freshness" ≈ network‑first (with timeout + fallback to cache)
strategy: "performance" ≈ cache‑first (stale‑while‑revalidate style)
Other key fields:
maxSize: max number of entries (per group) stored in the cache.
maxAge: how long cached responses are considered fresh (e.g. "1h", "7d").
timeout: only for "freshness"; if network doesn’t respond in time, fall back to cache.
4. Example API usage that benefits from caching
Create a simple service that hits two kinds of endpoints (critical vs non‑critical).
// src/app/services/posts.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class PostsService {
private readonly baseUrl = 'https://api.example.com/v1';
constructor(private http: HttpClient) {}
getCriticalData(): Observable<any> {
return this.http.get(`${this.baseUrl}/critical/dashboard`);
}
getNonCriticalData(): Observable<any> {
return this.http.get(`${this.baseUrl}/noncritical/recommendations`);
}
}
Then use it in a component:
// src/app/home/home.component.ts
import { Component, OnInit } from '@angular/core';
import { PostsService } from '../services/posts.service';
@Component({
selector: 'app-home',
template: `
<h1>Dashboard</h1>
<section *ngIf="criticalData">
<h2>Critical</h2>
<pre>{{ criticalData | json }}</pre>
</section>
<section *ngIf="nonCriticalData">
<h2>Non-critical</h2>
<pre>{{ nonCriticalData | json }}</pre>
</section>
`
})
export class HomeComponent implements OnInit {
criticalData: any;
nonCriticalData: any;
constructor(private posts: PostsService) {}
ngOnInit(): void {
this.posts.getCriticalData().subscribe((data) => (this.criticalData = data));
this.posts.getNonCriticalData().subscribe((data) => (this.nonCriticalData = data));
}
}
With the earlier ngsw-config.json:
5. Tuning and more advanced strategies
Some useful patterns:
5.1. Separate short‑lived vs long‑lived APIs
"dataGroups": [
{
"name": "user-profile",
"urls": ["https://api.example.com/v1/user/profile"],
"cacheConfig": {
"maxSize": 10,
"maxAge": "12h",
"strategy": "freshness",
"timeout": "3s"
}
},
{
"name": "lookup-tables",
"urls": ["https://api.example.com/v1/lookups/**"],
"cacheConfig": {
"maxSize": 50,
"maxAge": "30d",
"strategy": "performance"
}
}
]
- Frequently changing user data →
freshness, short maxAge.
- Almost static lookups →
performance, long maxAge.
5.2. Route‑based caching via assetGroups
Lazy-loaded route bundles are just JS files; they’re covered by your app-shell asset group:
{
"name": "app-shell",
"installMode": "prefetch",
"updateMode": "prefetch",
"resources": {
"files": [
"/index.html",
"/*.css",
"/*.js" // includes lazy-loaded route chunks
]
}
}
This makes navigation to lazy routes fast after the first online visit.
5.3. Offline UX: show “Offline” UI but serve app shell from SW
Angular’s service worker always serves index.html for navigations, so you get your app shell even offline. For user feedback:
// simple online-status service or component logic
import { Component, OnDestroy, OnInit } from '@angular/core';
import { fromEvent, merge, of, Subscription } from 'rxjs';
import { mapTo } from 'rxjs/operators';
@Component({
selector: 'app-root',
template: `
<div *ngIf="!online" class="offline-banner">
You are offline. Some data may be outdated.
</div>
<router-outlet></router-outlet>
`,
styles: [`.offline-banner { background:#ffcc00; padding:8px; }`]
})
export class AppComponent implements OnInit, OnDestroy {
online = true;
private sub?: Subscription;
ngOnInit(): void {
const online$ = fromEvent(window, 'online').pipe(mapTo(true));
const offline$ = fromEvent(window, 'offline').pipe(mapTo(false));
this.sub = merge(of(navigator.onLine), online$, offline$)
.subscribe(status => this.online = status);
}
ngOnDestroy() {
this.sub?.unsubscribe();
}
}
6. Build and test as a PWA
-
Build for production (service worker only runs in prod build):
ng build --configuration production
-
Serve the dist folder with an HTTP server (not ng serve):
npx http-server -p 8080 -c-1 dist/angular-pwa-demo/browser
-
Open http://localhost:8080 in Chrome:
- Check Application → Service Workers in DevTools.
- You should see
ngsw-worker.js registered.
- Go to Application → Cache Storage to inspect caches created for:
ngsw:app-shell:...
ngsw:data:api-...
- Toggle Offline in DevTools Network panel and refresh to see offline behavior.
-
Run Lighthouse (Chrome DevTools → Lighthouse / “PWAs”) to verify:
- Installability
- Offline capability
- PWA best practices
7. Optional: Prompt user when a new version is cached
This isn’t caching per se, but pairs well with service workers:
// src/app/core/update.service.ts
import { Injectable } from '@angular/core';
import { SwUpdate } from '@angular/service-worker';
import { filter } from 'rxjs/operators';
@Injectable({ providedIn: 'root' })
export class UpdateService {
constructor(private swUpdate: SwUpdate) {
if (this.swUpdate.isEnabled) {
this.swUpdate.versionUpdates
.pipe(filter((event) => event.type === 'VERSION_READY'))
.subscribe(() => {
const reload = confirm('A new version is available. Reload now?');
if (reload) {
document.location.reload();
}
});
}
}
}
Inject UpdateService in your root component so it initializes.
8. Summary of “advanced” caching you now have
- App shell pre‑cached for near‑instant startup after first load.
- Static assets cached lazily and updated in the background.
- Critical API:
- Network‑first with timeout → ensures fresh data when online.
- Falls back to cache offline or on slow network.
- Non‑critical / CDN data:
- Cache‑first for speed and resilience.
- Periodic background updates based on
maxAge.
- Offline‑aware UI: app shell is served offline, with an offline indicator.
If you tell me your actual API base URLs and which resources are critical vs non‑critical, I can propose a tailored ngsw-config.json for your project.