{ "id": "guide/service-worker-config", "title": "Service worker configuration", "contents": "\n\n\n
\n mode_edit\n
\n\n\n
\n

Service worker configurationlink

\n

Prerequisiteslink

\n

A basic understanding of the following:

\n\n
\n

The ngsw-config.json configuration file specifies which files and data URLs the Angular service\nworker should cache and how it should update the cached files and data. The Angular CLI\nprocesses the configuration file during ng build. Manually, you can process it with the\nngsw-config tool (where <project-name> is the name of the project being built):

\n\n./node_modules/.bin/ngsw-config ./dist/<project-name> ./ngsw-config.json [/base/href]\n\n

The configuration file uses the JSON format. All file paths must begin with /, which corresponds\nto the deployment directory—usually dist/<project-name> in CLI projects.

\n\n

Unless otherwise noted, patterns use a limited glob format:

\n\n

Example patterns:

\n\n

Each section of the configuration file is described below.

\n

appDatalink

\n

This section enables you to pass any data you want that describes this particular version of the app.\nThe SwUpdate service includes that data in the update notifications. Many apps use this section to provide additional information for the display of UI popups, notifying users of the available update.

\n\n

indexlink

\n

Specifies the file that serves as the index page to satisfy navigation requests. Usually this is /index.html.

\n

assetGroupslink

\n

Assets are resources that are part of the app version that update along with the app. They can include resources loaded from the page's origin as well as third-party resources loaded from CDNs and other external URLs. As not all such external URLs may be known at build time, URL patterns can be matched.

\n

This field contains an array of asset groups, each of which defines a set of asset resources and the policy by which they are cached.

\n\n{\n \"assetGroups\": [\n {\n ...\n },\n {\n ...\n }\n ]\n}\n\n
\n

When the ServiceWorker handles a request, it checks asset groups in the order in which they appear in ngsw-config.json.\nThe first asset group that matches the requested resource handles the request.

\n

It is recommended that you put the more specific asset groups higher in the list.\nFor example, an asset group that matches /foo.js should appear before one that matches *.js.

\n
\n

Each asset group specifies both a group of resources and a policy that governs them. This policy determines when the resources are fetched and what happens when changes are detected.

\n

Asset groups follow the Typescript interface shown here:

\n\ninterface AssetGroup {\n name: string;\n installMode?: 'prefetch' | 'lazy';\n updateMode?: 'prefetch' | 'lazy';\n resources: {\n files?: string[];\n urls?: string[];\n };\n cacheQueryOptions?: {\n ignoreSearch?: boolean;\n };\n}\n\n

namelink

\n

A name is mandatory. It identifies this particular group of assets between versions of the configuration.

\n

installModelink

\n

The installMode determines how these resources are initially cached. The installMode can be either of two values:

\n\n

Defaults to prefetch.

\n

updateModelink

\n

For resources already in the cache, the updateMode determines the caching behavior when a new version of the app is discovered. Any resources in the group that have changed since the previous version are updated in accordance with updateMode.

\n\n

Defaults to the value installMode is set to.

\n

resourceslink

\n

This section describes the resources to cache, broken up into the following groups:

\n\n

cacheQueryOptionslink

\n

These options are used to modify the matching behavior of requests. They are passed to the browsers Cache#match function. See MDN for details. Currently, only the following options are supported:

\n\n

dataGroupslink

\n

Unlike asset resources, data requests are not versioned along with the app. They're cached according to manually-configured policies that are more useful for situations such as API requests and other data dependencies.

\n

This field contains an array of data groups, each of which defines a set of data resources and the policy by which they are cached.

\n\n{\n \"dataGroups\": [\n {\n ...\n },\n {\n ...\n }\n ]\n}\n\n
\n

When the ServiceWorker handles a request, it checks data groups in the order in which they appear in ngsw-config.json.\nThe first data group that matches the requested resource handles the request.

\n

It is recommended that you put the more specific data groups higher in the list.\nFor example, a data group that matches /api/foo.json should appear before one that matches /api/*.json.

\n
\n

Data groups follow this Typescript interface:

\n\nexport interface DataGroup {\n name: string;\n urls: string[];\n version?: number;\n cacheConfig: {\n maxSize: number;\n maxAge: string;\n timeout?: string;\n strategy?: 'freshness' | 'performance';\n };\n cacheQueryOptions?: {\n ignoreSearch?: boolean;\n };\n}\n\n

namelink

\n

Similar to assetGroups, every data group has a name which uniquely identifies it.

\n

urlslink

\n

A list of URL patterns. URLs that match these patterns are cached according to this data group's policy. Only non-mutating requests (GET and HEAD) are cached.

\n\n

versionlink

\n

Occasionally APIs change formats in a way that is not backward-compatible. A new version of the app may not be compatible with the old API format and thus may not be compatible with existing cached resources from that API.

\n

version provides a mechanism to indicate that the resources being cached have been updated in a backwards-incompatible way, and that the old cache entries—those from previous versions—should be discarded.

\n

version is an integer field and defaults to 1.

\n

cacheConfiglink

\n

This section defines the policy by which matching requests will be cached.

\n

maxSizelink

\n

(required) The maximum number of entries, or responses, in the cache. Open-ended caches can grow in unbounded ways and eventually exceed storage quotas, calling for eviction.

\n

maxAgelink

\n

(required) The maxAge parameter indicates how long responses are allowed to remain in the cache before being considered invalid and evicted. maxAge is a duration string, using the following unit suffixes:

\n\n

For example, the string 3d12h will cache content for up to three and a half days.

\n

timeoutlink

\n

This duration string specifies the network timeout. The network timeout is how long the Angular service worker will wait for the network to respond before using a cached response, if configured to do so. timeout is a duration string, using the following unit suffixes:

\n\n

For example, the string 5s30u will translate to five seconds and 30 milliseconds of network timeout.

\n

strategylink

\n

The Angular service worker can use either of two caching strategies for data resources.

\n\n
\n

You can also emulate a third strategy, staleWhileRevalidate, which returns cached data (if available), but also fetches fresh data from the network in the background for next time.\nTo use this strategy set strategy to freshness and timeout to 0u in cacheConfig.

\n

This will essentially do the following:

\n
    \n
  1. Try to fetch from the network first.
  2. \n
  3. If the network request does not complete after 0ms (i.e. immediately), fall back to the cache (ignoring cache age).
  4. \n
  5. Once the network request completes, update the cache for future requests.
  6. \n
  7. If the resource does not exist in the cache, wait for the network request anyway.
  8. \n
\n
\n

cacheQueryOptionslink

\n

See assetGroups for details.

\n

navigationUrlslink

\n

This optional section enables you to specify a custom list of URLs that will be redirected to the index file.

\n

Handling navigation requestslink

\n

The ServiceWorker will redirect navigation requests that don't match any asset or data group to the specified index file. A request is considered to be a navigation request if:

\n
    \n
  1. Its mode is navigation.
  2. \n
  3. It accepts a text/html response (as determined by the value of the Accept header).
  4. \n
  5. Its URL matches certain criteria (see below).
  6. \n
\n

By default, these criteria are:

\n
    \n
  1. The URL must not contain a file extension (i.e. a .) in the last path segment.
  2. \n
  3. The URL must not contain __.
  4. \n
\n
\n

To configure whether navigation requests are sent through to the network or not, see the navigationRequestStrategy section.

\n
\n

Matching navigation request URLslink

\n

While these default criteria are fine in most cases, it is sometimes desirable to configure different rules. For example, you may want to ignore specific routes (that are not part of the Angular app) and pass them through to the server.

\n

This field contains an array of URLs and glob-like URL patterns that will be matched at runtime. It can contain both negative patterns (i.e. patterns starting with !) and non-negative patterns and URLs.

\n

Only requests whose URLs match any of the non-negative URLs/patterns and none of the negative ones will be considered navigation requests. The URL query will be ignored when matching.

\n

If the field is omitted, it defaults to:

\n\n[\n '/**', // Include all URLs.\n '!/**/*.*', // Exclude URLs to files.\n '!/**/*__*', // Exclude URLs containing `__` in the last segment.\n '!/**/*__*/**', // Exclude URLs containing `__` in any other segment.\n]\n\n\n

navigationRequestStrategylink

\n

This optional property enables you to configure how the service worker handles navigation requests:

\n\n{\n \"navigationRequestStrategy\": \"freshness\"\n}\n\n

Possible values:

\n\n
\n

The freshness strategy usually results in more requests sent to the server, which can increase response latency.\nIt is recommended that you use the default performance strategy whenever possible.

\n
\n\n \n
\n\n\n" }