Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting service worker to exclude certain urls only

I built an app using create react which by default includes a service worker. I want the app to be run anytime someone enters the given url except when they go to /blog/, which is serving a set of static content. I use react router in the app to catch different urls.

I have nginx setup to serve /blog/ and it works fine if someone visits /blog/ without visiting the react app first. However because the service worker has a scope of ./, anytime someone visits any url other than /blog/, the app loads the service worker. From that point on, the service worker bypasses a connection to the server and /blog/ loads the react app instead of the static contents.

Is there a way to have the service worker load on all urls except /blog/?

like image 271
user3577166 Avatar asked Aug 13 '17 18:08

user3577166


2 Answers

So, considering, you have not posted any code relevant to the service worker, you might consider adding a simple if conditional inside the code block for fetch

This code block should already be there inside your service worker.Just add the conditionals

self.addEventListener( 'fetch', function ( event ) {

    if ( event.request.url.match( '^.*(\/blog\/).*$' ) ) {
        return false;
    }
     // OR

    if ( event.request.url.indexOf( '/blog/' ) !== -1 ) {
        return false;
    }
    //    **** rest of your service worker code ****

note you can either use the regex or the prototype method indexOf. per your whim.

the above would direct your service worker, to just do nothing when the url matches /blog/

like image 65
Schrodinger's cat Avatar answered Nov 18 '22 13:11

Schrodinger's cat


Another way to blacklist URLs, i.e., exclude them from being served from cache, when you're using Workbox can be achieved with workbox.routing.registerNavigationRoute:

workbox.routing.registerNavigationRoute("/index.html", {
  blacklist: [/^\/api/,/^\/admin/],
});

The example above demonstrates this for a SPA where all routes are cached and mapped into index.html except for any URL starting with /api or /admin.

like image 34
F Lekschas Avatar answered Nov 18 '22 13:11

F Lekschas