workboxworkbox-webpack-plugin

Workbox-webpack-plugin nested urls sw registration


I have nested routes in my react app, like https://my-app.com/someroute/new and on https://my-app.com/someroute level service worker registration works fine, but on https://my-app.com/someroute/new level it fails with

Error during service worker registration: DOMException: Failed to register a ServiceWorker for scope ('https://my-app.com/someroute/') with script ('https://my-app.com/someroute/service-worker.js'): The script has an unsupported MIME type ('text/html').

I've tried to set directoryIndex equal to '../' but also no success.

My workbox-plugin config is here:

new GenerateSW({
    cacheId: 'my-app',
    skipWaiting: true,
    clientsClaim: true,
    exclude: [/\.map$/, /^manifest.*\.js(?:on)?$/, /\.html$/],
}),

Solution

  • That error means that when your web app requests the URL https://my-app.com/someroute/service-worker.js from your web server, instead of returning the JavaScript contents of service-worker.js, it's returning an HTML document. This is presumably a "404 not found" error document, because the web server doesn't think that the https://my-app.com/someroute/service-worker.js exists.

    The way to resolve this is to ensure that there's a valid service-worker.js file that lives in the /someroute/ directory under your web server's root.

    The GenerateSW workbox-webpack-plugin has a swDest property that can be used to control the location that the service work file will be output. Setting it to swDest: '/someroute/service-worker.js' might be sufficient to solve your problem.