Search code examples
reactjsreact-routerworkbox

React Workbox PWA App on Subdirectory with react router custom basename


I'm working on react Project which uses react-router as its routing Library. since I want to run that project on a subdirectory of the website, I set the react-router basename attribute to 'my' in my app.js file.

App.js

<BrowserRouter basename={'/my'}>

and also I set the homepage property in the package.json file

package.json

"homepage": "/my",

the app works charming until I decided to make the app PWA using workBox.

craco.config.js Or Webpack.config.js

 plugins: [
          new InjectManifest({
            swSrc: "./src/src-sw.js",
            swDest: "sw.js",
          }),
        ],

I tried to build and check if it's working, but it simply doesn't show me the any registered workers On the Application tab in the Chrome Developer Console
but as soon as I remove the basename attribute and homepage property, everything works, and the service worker and manifest.json files appear Application Tab

Application Tab on chrome Developer Console

Console Tab

Manifest section On Application tab


Solution

  • After struggling with the Problem and reading so many articles and issues on Gits and etc, I found that the service worker has the scope and the default scope is / or root of your host. if you want to extend the scope and run service worker from the subdirectory you need to set Service-Worker-Allowed header.

    References:

    Service Workers Documentation on MDN

    Two HTTP headers related to Service Workers you never may have heard of- by Thomas Steiner

    How exactly add "Service-Worker-Allowed" to register service worker scope in upper folder