Search code examples
reactjsprogressive-web-appsworkbox

React and Serviceworker (Workbox)


Im trying to figure out how I can combine my react app with workbox as my serviceworker. No matter what Im doing I always get the same error, while trying to register my serviceworker.

Uncaught (in promise) DOMException: Failed to register a ServiceWorker: The script has an unsupported MIME type ('text/html').

After I`ve done some research, most of the solutions turned out that it was caused by the dev environment. Is this true? And if so, how I can register a serviceworker, especially workbox, in a dev environment.

My Code Snippet inside my index.js

if( 'serviceWorker' in navigator ) {
   console.log("Supported!")
   navigator.serviceWorker
                   .register( 'sw.js' , { scope : ' ' } )
                   .then( function( ) {
                       console.log('Congratulations!!Service Worker Registered');
                   })
                   .catch( function() {
                       console.log(`Aagh! Some kind of Error :- `);
                   });
} else {
console.log("Not supported")
}

There's nothing more to my sw.js than a simple console.log


Solution

  • Couple of things to check, 1) create-react-app created a PWA app out of the box now(with SW and manifest.json files). Make sure you are not conflicting with the files created by that. I would recommend using what comes out of the box, unless you have an explicit reason to use Workbox, which should work with any framework/no framework, try what comes natively.

    2) Make sure you are running your app in a server which supports HTTPS (with a cert) and service worker.