{ "id": "guide/service-worker-devops", "title": "Service worker in production", "contents": "\n\n\n
This page is a reference for deploying and supporting production apps that use the Angular service worker. It explains how the Angular service worker fits into the larger production environment, the service worker's behavior under various conditions, and available resources and fail-safes.
\nA basic understanding of the following:
\n\nConceptually, you can imagine the Angular service worker as a forward cache or a CDN edge that is installed in the end user's web browser. The service worker's job is to satisfy requests made by the Angular app for resources or data from a local cache, without needing to wait for the network. Like any cache, it has rules for how content is expired and updated.
\n\nIn the context of an Angular service worker, a \"version\" is a collection of resources that represent a specific build of the Angular app. Whenever a new build of the app is deployed, the service worker treats that build as a new version of the app. This is true even if only a single file is updated. At any given time, the service worker may have multiple versions of the app in its cache and it may be serving them simultaneously. For more information, see the App tabs section below.
\nTo preserve app integrity, the Angular service worker groups all files into a version together. The files grouped into a version usually include HTML, JS, and CSS files. Grouping of these files is essential for integrity because HTML, JS, and CSS files frequently refer to each other and depend on specific content. For example, an index.html
file might have a <script>
tag that references bundle.js
and it might attempt to call a function startApp()
from within that script. Any time this version of index.html
is served, the corresponding bundle.js
must be served with it. For example, assume that the startApp()
function is renamed to runApp()
in both files. In this scenario, it is not valid to serve the old index.html
, which calls startApp()
, along with the new bundle, which defines runApp()
.
This file integrity is especially important when lazy loading modules.\nA JS bundle may reference many lazy chunks, and the filenames of the\nlazy chunks are unique to the particular build of the app. If a running\napp at version X
attempts to load a lazy chunk, but the server has\nupdated to version X + 1
already, the lazy loading operation will fail.
The version identifier of the app is determined by the contents of all\nresources, and it changes if any of them change. In practice, the version\nis determined by the contents of the ngsw.json
file, which includes\nhashes for all known content. If any of the cached files change, the file's\nhash will change in ngsw.json
, causing the Angular service worker to\ntreat the active set of files as a new version.
With the versioning behavior of the Angular service worker, an application\nserver can ensure that the Angular app always has a consistent set of files.
\nEvery time the user opens or refreshes the application, the Angular service worker\nchecks for updates to the app by looking for updates to the ngsw.json
manifest. If\nan update is found, it is downloaded and cached automatically, and will be served\nthe next time the application is loaded.
One of the potential side effects of long caching is inadvertently\ncaching an invalid resource. In a normal HTTP cache, a hard refresh\nor cache expiration limits the negative effects of caching an invalid\nfile. A service worker ignores such constraints and effectively long\ncaches the entire app. Consequently, it is essential that the service worker\ngets the correct content.
\nTo ensure resource integrity, the Angular service worker validates\nthe hashes of all resources for which it has a hash. Typically for\nan app created with the Angular CLI, this is everything in the dist
directory covered by\nthe user's src/ngsw-config.json
configuration.
If a particular file fails validation, the Angular service worker\nattempts to re-fetch the content using a \"cache-busting\" URL\nparameter to eliminate the effects of browser or intermediate\ncaching. If that content also fails validation, the service worker\nconsiders the entire version of the app to be invalid and it stops\nserving the app. If necessary, the service worker enters a safe mode\nwhere requests fall back on the network, opting not to use its cache\nif the risk of serving invalid, broken, or outdated content is high.
\nHash mismatches can occur for a variety of reasons:
\nngsw.json
being updated. The reverse could also happen resulting in an updated ngsw.json
without updated resources.The only resources that have hashes in the ngsw.json
\nmanifest are resources that were present in the dist
\ndirectory at the time the manifest was built. Other\nresources, especially those loaded from CDNs, have\ncontent that is unknown at build time or are updated\nmore frequently than the app is deployed.
If the Angular service worker does not have a hash to validate\na given resource, it still caches its contents but it honors\nthe HTTP caching headers by using a policy of \"stale while\nrevalidate.\" That is, when HTTP caching headers for a cached\nresource indicate that the resource has expired, the Angular\nservice worker continues to serve the content and it attempts\nto refresh the resource in the background. This way, broken\nunhashed resources do not remain in the cache beyond their\nconfigured lifetimes.
\n\nIt can be problematic for an app if the version of resources\nit's receiving changes suddenly or without warning. See the\nVersions section above\nfor a description of such issues.
\nThe Angular service worker provides a guarantee: a running app\nwill continue to run the same version of the app. If another\ninstance of the app is opened in a new web browser tab, then\nthe most current version of the app is served. As a result,\nthat new tab can be running a different version of the app\nthan the original tab.
\nIt's important to note that this guarantee is stronger\nthan that provided by the normal web deployment model. Without\na service worker, there is no guarantee that code lazily loaded\nlater in a running app is from the same version as the initial\ncode for the app.
\nThere are a few limited reasons why the Angular service worker\nmight change the version of a running app. Some of them are\nerror conditions:
\nThe Angular service worker is aware of which versions are in\nuse at any given moment and it cleans up versions when\nno tab is using them.
\nOther reasons the Angular service worker might change the version\nof a running app are normal events:
\nSwUpdate
service.The Angular service worker is a small script that runs in web browsers.\nFrom time to time, the service worker will be updated with bug\nfixes and feature improvements.
\nThe Angular service worker is downloaded when the app is first opened\nand when the app is accessed after a period of inactivity. If the\nservice worker has changed, the service worker will be updated in the background.
\nMost updates to the Angular service worker are transparent to the\napp—the old caches are still valid and content is still served\nnormally. However, occasionally a bugfix or feature in the Angular\nservice worker requires the invalidation of old caches. In this case,\nthe app will be refreshed transparently from the network.
\nIn some cases, you may want to bypass the service worker entirely and let the browser handle the\nrequest instead. An example is when you rely on a feature that is currently not supported in service\nworkers (e.g.\nreporting progress on uploaded files).
\nTo bypass the service worker you can set ngsw-bypass
as a request header, or as a query parameter.\n(The value of the header or query parameter is ignored and can be empty or omitted.)
Occasionally, it may be necessary to examine the Angular service\nworker in a running state to investigate issues or to ensure that\nit is operating as designed. Browsers provide built-in tools for\ndebugging service workers and the Angular service worker itself\nincludes useful debugging features.
\nThe Angular service worker exposes debugging information under\nthe ngsw/
virtual directory. Currently, the single exposed URL\nis ngsw/state
. Here is an example of this debug page's contents:
The first line indicates the driver state:
\nNORMAL
indicates that the service worker is operating normally and is not in a degraded state.
There are two possible degraded states:
\nEXISTING_CLIENTS_ONLY
: the service worker does not have a\nclean copy of the latest known version of the app. Older cached\nversions are safe to use, so existing tabs continue to run from\ncache, but new loads of the app will be served from the network.\nThe service worker will try to recover from this state when a new\nversion of the application is detected and installed (that is,\nwhen a new ngsw.json
is available).
SAFE_MODE
: the service worker cannot guarantee the safety of\nusing cached data. Either an unexpected error occurred or all\ncached versions are invalid. All traffic will be served from the\nnetwork, running as little service worker code as possible.
In both cases, the parenthetical annotation provides the\nerror that caused the service worker to enter the degraded state.
\nBoth states are temporary; they are saved only for the lifetime of the ServiceWorker\ninstance.\nThe browser sometimes terminates an idle service worker to conserve memory and\nprocessor power, and creates a new service worker instance in response to\nnetwork events. The new instance starts in the NORMAL
mode, regardless of the\nstate of the previous instance.
This is the SHA1 hash of the most up-to-date version of the app that the service worker knows about.
\nThis indicates the last time the service worker checked for a new version, or update, of the app. never
indicates that the service worker has never checked for an update.
In this example debug file, the update check is currently scheduled, as explained the next section.
\nIn this example, the service worker has one version of the app cached and\nbeing used to serve two different tabs. Note that this version hash\nis the \"latest manifest hash\" listed above. Both clients are on the\nlatest version. Each client is listed by its ID from the Clients
\nAPI in the browser.
The Idle Task Queue is the queue of all pending tasks that happen\nin the background in the service worker. If there are any tasks\nin the queue, they are listed with a description. In this example,\nthe service worker has one such task scheduled, a post-initialization\noperation involving an update check and cleanup of stale caches.
\nThe last update tick/run counters give the time since specific\nevents happened related to the idle queue. The \"Last update run\"\ncounter shows the last time idle tasks were actually executed.\n\"Last update tick\" shows the time since the last event after\nwhich the queue might be processed.
\nErrors that occur within the service worker will be logged here.
\nBrowsers such as Chrome provide developer tools for interacting\nwith service workers. Such tools can be powerful when used properly,\nbut there are a few things to keep in mind.
\nWhen using developer tools, the service worker is kept running\nin the background and never restarts. This can cause behavior with Dev\nTools open to differ from behavior a user might experience.
\nIf you look in the Cache Storage viewer, the cache is frequently\nout of date. Right click the Cache Storage title and refresh the caches.
\nStopping and starting the service worker in the Service Worker\npane triggers a check for updates.
\nLike any complex system, bugs or broken configurations can cause\nthe Angular service worker to act in unforeseen ways. While its\ndesign attempts to minimize the impact of such problems, the\nAngular service worker contains several failsafe mechanisms in case\nan administrator ever needs to deactivate the service worker quickly.
\nTo deactivate the service worker, remove or rename the\nngsw.json
file. When the service worker's request\nfor ngsw.json
returns a 404
, then the service worker\nremoves all of its caches and de-registers itself,\nessentially self-destructing.
Also included in the @angular/service-worker
NPM package is a small\nscript safety-worker.js
, which when loaded will unregister itself\nfrom the browser. This script can be used as a last resort to get rid\nof unwanted service workers already installed on client pages.
It's important to note that you cannot register this worker directly,\nas old clients with cached state may not see a new index.html
which\ninstalls the different worker script. Instead, you must serve the\ncontents of safety-worker.js
at the URL of the Service Worker script\nyou are trying to unregister, and must continue to do so until you are\ncertain all users have successfully unregistered the old worker. For\nmost sites, this means that you should serve the safety worker at the\nold Service Worker URL forever.
This script can be used both to deactivate @angular/service-worker
\nas well as any other Service Workers which might have been served in\nthe past on your site.
It is important to note that service workers don't work behind redirect. You\nmay have already encountered the error The script resource is behind a redirect, which is disallowed
.
This can be a problem if you have to change your app's location. If you setup\na redirect from the old location (for example example.com
) to the new\nlocation (for example www.example.com
) the worker will stop working.\nAlso, the redirect won't even trigger for users who are loading the site\nentirely from Service Worker. The old worker (registered at example.com
)\ntries to update and sends requests to the old location example.com
which\nget redirected to the new location www.example.com
and create the error\nThe script resource is behind a redirect, which is disallowed
.
To remedy this, you may need to kill the old worker using one of the above\ntechniques (Fail-safe or Safety Worker).
\nYou may also be interested in the following:
\n\n\n \n