2

I have app using create-react-app and service-worker generated on-a-build.

I checked out a lot of issues and articles, but still not found usable answer.

What is a best practice to add something like urlBlockList to create-react-app service worker?


I think react eject is not the most appropriate solution

Prvz
  • 203
  • 3
  • 8
  • Have you looked at https://stackoverflow.com/questions/45663796/setting-service-worker-to-exclude-certain-urls-only ? – R.Duteil Oct 19 '18 at 12:29
  • yes, but service-worker code contains very clear phrase "do not modify this generated code", that is why i think - it's not best practice way. btw it is minified – Prvz Oct 19 '18 at 14:38
  • I automated modification of the build/service-worker.js code after the create-react-app build process here - https://stackoverflow.com/questions/49776235/how-do-i-exclude-urls-from-service-worker-scope-in-create-react-app-without-ha/63344095#63344095 Should be fine. Nothing is going to be modifying that file after it's released to production. – Wayne Bloss Aug 10 '20 at 16:40

2 Answers2

2

Resolved

Best solution that I found - use https://github.com/liuderchi/sw-precache-cra and add unwanted urls to custom sw-config

Example:

// sw-config.js
module.exports = {
  runtimeCaching: [
    {
      urlPattern: '/unwantedurl',
      handler: 'networkFirst',
    },
  ],
};
Prvz
  • 203
  • 3
  • 8
2

Here's a solution that works with CRA 3:

  1. Add react-app-rewired to your project, e.g.: yarn add react-app-rewired --save-dev
  2. Replace react-scripts in the scripts section of your package.json with react-app-rewired
  3. Place a file called config-overrides.js in the root of your project. In this file you can add entries to the service-worker configuration. For example:
module.exports = function override(config, env) {
  const swPrecacheConfig = config.plugins.find(
     plugin => plugin.constructor.name === "GenerateSW"
  );
  // Prevent some URLs from being cached by the service worker
  const blacklist = swPrecacheConfig.config.navigateFallbackBlacklist;
  blacklist.push(/\/oauth2\/authorization\//);
  blacklist.push(/\/login\/oauth2\//);
  return config;
};

The configuration above excludes urls with /oauth2/authorization/ and /login/oauth2/ from the service-worker.

Rob van der Leek
  • 1,486
  • 15
  • 13