Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk4 min

How to Add a Custom Service Worker Script to an Angular App

Extend Angular’s service worker with custom event handling while retaining its caching and update behavior. Learn how to configure, register, test, and troubleshoot the script.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To add custom service-worker behavior to an Angular app while keeping Angular’s caching and update handling, create a worker that imports ngsw-worker.js first, add your event listeners, copy the custom file into the build output, and register it with provideServiceWorker. Use ngsw-config.json instead when you only need to change which resources Angular caches or how it caches them.

Choose configuration or a custom worker

Start by identifying what needs to change. Angular’s service worker configuration file controls caching for application assets and data requests. Its asset groups and data groups let you define what is cached and the relevant caching behavior.

As an Amazon Associate I earn from qualifying purchases.

  • Change cache matching or policy: adjust ngsw-config.json.
  • Handle browser events or add behavior outside Angular’s configured caching: extend the Angular worker with a custom script.
  • Need advanced caching or offline capabilities: consider native browser APIs. Angular describes its service worker as a basic utility for simple offline support, says it will receive no new features beyond security fixes, and recommends native APIs for more advanced needs. See the Angular service worker overview.

Examples of custom event behavior include reacting to notification clicks or handling background sync. A custom script is not a substitute for checking whether a cache configuration change already solves the problem.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Extend Angular’s worker

Create a custom service worker file in your application source. The key step is importing Angular’s worker before adding custom listeners; this preserves access to Angular’s caching and update functionality. The documented extension pattern is described in Angular’s custom service worker scripts guide.

importScripts('./ngsw-worker.js');

(() => {
  self.addEventListener('notificationclick', event => {
    event.waitUntil((async () => {
      // Add application-specific notification-click behavior.
    })());
  });

  self.addEventListener('sync', event => {
    if (event.tag === 'my-background-sync') {
      event.waitUntil((async () => {
        // Add application-specific background-sync behavior.
      })());
    }
  });
})();

The event names and tag above illustrate where application logic belongs; they do not provide a complete notification or sync implementation. Use event.waitUntil() for asynchronous work so the browser knows the event has work to finish before it can terminate the worker. Handle rejected promises and other failures deliberately. Angular also recommends wrapping custom code in an immediately invoked function expression (IIFE) to limit global-scope pollution.

Include the file in the build and register it

The browser must be able to fetch the custom script from the deployed application. Add it to the build assets in the project’s Angular build configuration, and confirm that its output location matches the path you plan to register. Asset configuration varies by project, so verify the generated build output rather than assuming a source-file path is also the deployed URL.

Register the script through Angular’s provider in the application providers:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
provideServiceWorker('custom-sw.js', options)

The first argument is the worker script path; the optional second argument is a SwRegistrationOptions object. Angular documents options for enabling registration, script type, scope, update-via-cache behavior, and registration timing. The stable API documents registerWhenStable:30000 as the default registration strategy; check the API documentation for the Angular version used by your application, since API behavior can evolve. See provideServiceWorker and SwRegistrationOptions.

Test the production build and deployed scope

Service workers require a secure context: use HTTPS in deployment, with localhost as the development exception. Also account for browsers where service workers are unsupported rather than assuming registration succeeds everywhere. Angular’s overview covers these support and security-context considerations.

  1. Build the app with its production configuration. Angular’s getting-started guide describes the standard setup with ng add @angular/pwa, creation of ngsw-config.json, and local testing of a production configuration.
  2. Serve the built app from a suitable context. Confirm that both custom-sw.js and ngsw-worker.js resolve at the expected deployed paths.
  3. Test in a private or incognito window. Angular recommends this to reduce interference from an older worker or cached state.
  4. Verify the behavior you added. Exercise the relevant event, confirm asynchronous work completes, and check that errors are handled. Test both development and production as appropriate for the app.
  5. Check the worker’s scope and supported browsers. A wrong path or scope can prevent the expected pages from being controlled by the worker.

Check cache configuration before debugging custom code

If a request is cached unexpectedly or not cached at all, the cause may be ngsw-config.json rather than the custom event handler. Angular evaluates asset groups in order, and the first matching data group handles a request. Put more specific data groups before broader ones. Its configuration guide also notes that glob patterns may partially match URLs and that special regular-expression characters may need escaping. See Service Worker configuration file.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Understand updates and recovery

Angular’s deployment guidance says hashed resources are checked for integrity. A browser installs an updated service worker when the worker script is byte-different; changing only response headers does not trigger reinstallation. If a header-only change must trigger installation, Angular documents using a versioned script URL. See Service worker devops.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a problematic registration or cache, Angular also documents recovery approaches that rename or remove ngsw.json and use the package’s safety-worker.js to remove unwanted service-worker registrations and caches. These are operational measures, not routine update steps: validate their effects against the application’s deployment setup before using them.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.