Making Angular apps resilient with service worker precaching

Users on flaky or unavailable networks often hit broken functionality in web apps. A service worker that precaches assets can intercept requests and serve responses from a local cache, bypassing the network entirely. Once the app's key assets are stored locally, startup and navigation can stay fast even when connectivity drops.

The Angular team ships a service worker module built specifically for Angular and integrated with the Angular CLI. It handles precaching with little manual configuration.

Setting up the Angular service worker

Add the service worker to your project with the CLI:

ng add @angular/pwa

This adds @angular/service-worker and @angular/pwa to package.json. The ng-add schematic also creates a default ngsw-config.json in the project root, which you will use to control what the service worker caches.

Build the project for production:

ng build --prod

The build output inside the dist directory includes a generated ngsw.json manifest. This file instructs the Angular service worker on which assets to cache. It is created at build time from the configuration in ngsw-config.json and the actual assets produced by the build.

To see precaching in action, serve the production assets over HTTP and inspect the network tab in Chrome DevTools (Control+Shift+J, or Command+Option+J on Mac). You will notice ngsw-worker.js downloading static assets in the background:

Sample app

That is the service worker following the manifest and precaching the specified files.

Customizing which assets get precached

The default configuration does not precache every static asset. In the example app, nyan.png is missing from the requests because no rule matches it. To include it, update the app asset group in ngsw-config.json:

{
  "$schema": "./node_modules/@angular/service-worker/config/schema.json",
  "index": "/index.html",
  "assetGroups": [
    {
      "name": "app",
      "installMode": "prefetch",
      "resources": {
      "files": [
        "/favicon.ico",
        "/index.html",
        "/*.css",
        "/*.js",
        "/assets/*.png"
        ]
      }
    },
    ...
}

With that pattern in place, all PNG images under /assets belong to the app resource asset group. Because that group's installMode is prefetch, the service worker precaches every matching asset during installation, including the image.

To precache other files or folders, add or adjust the patterns in the same resource asset group. The configuration structure stays the same regardless of asset type.

Summary

Precaching with the Angular service worker keeps your app usable on poor connections by storing static assets locally ahead of time. The workflow is simple:

  1. Add @angular/pwa to the project.
  2. Edit ngsw-config.json to define which assets belong to which cached groups.