How to Exclude a Path in Angular Service Worker

How to Exclude a Path in Angular Service Worker

·

2 min read

This article is based on experience: I’ll share all the needed details because it took some time to find them and also test and exclude all the non-working solutions.

Requirements

This solution is needed when a service worker should not handle the request at all. Not just skip caching, but exactly: let the browser handle the request.

In my case, a request to EventSource should not be handled by a service worker because, after reaching the limit of EventSource streams (just 6), the page will not load at all. And if a service worker creates an EventSource stream, it will not be removed even when the page is closed, so the user can not even open a new tab (cool, right?).

There are other cases; I’ve just described one I’ve encountered.

Solution

The only working solution is prototyped here: GitHub comment link.

Do not waste your time on attempts to add the path to the ngsw-config.json file: nothing will work. navigationUrls, dataGroups with maxSize: 0 — that’s all for other cases and our service worker will still handle the request, even if it will not cache the request.

You’ll need to make a few changes.

First of all, create this file and put it to src folder of your app:

self.addEventListener('fetch', event => {
  if (event && 
      event.request && 
      event.request.url && 
      event.request.url.includes('/event-stream') // 🖍️
  ) {
    event.stopImmediatePropagation();
  }
});

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

replace /event-stream with the path you need, name this file as you want, I will reference it as sw.js in this article.

Then, edit angular.json or project.json (needed file will contain text “ngswConfigPath”), section targets/build/options/assets.

Add path to sw.js into this section (relative to the repository root).

Now, in app.module.ts or in some other file, if you use a fully standalone app, you should have a point when you add ServiceWorkerModule to modules or providers.

Replace the path to the file there: in my case, I’ve replaced ngsw-worker.js with ./sw.js.

Now Angular Service worker is wrapped and the path is excluded. You can improve the code, and change the conditions why requests should be excluded — you have the initial setup now.


💙 If you enjoy my articles, consider following me on Twitter, and/or subscribing to receive my new articles by email.

🎩️ If you or your company is looking for an Angular consultant, you can purchase my consultations on Upwork.


🖼
“Composition VIII”, Wassily Kandinsky, 1923