0

I hope the question has not been asked too many times. So, I wanted to create my own service worker file, in my React project. I called it 'sw.js' and put it in the src/ folder, the same folder that contains the 'index.js' file which contains all the jsx. The architecture of the React Project is :

  • node_modules -public -src -----index.js -----sw.js -package -package-lock -README

As soon as the page load, the service worker should register in the browser. However , on Firefox, I have the following error : "Failed to register/update a ServiceWorker for scope ‘http://localhost:3000/’: Bad Content-Type of ‘text/html’ received for script ‘http://localhost:3000/sw.js’. Must be a JavaScript MIME type."

"Service Worker Error DOMException: "The operation is insecure.""

I know that the error does not com from the code of registering the service worker itself, because it worked on a standard project with no react

here is the code registering the service worker in index.js :

render() {

    if ('serviceWorker' in navigator) {
        window.addEventListener('load', () => {
            console.log('Service Worker and Push is supported');

            navigator.serviceWorker.register('/sw.js')
                .then(swReg => {
                    console.log('Service Worker is registered', swReg);
                    this.setState({ swReg : swReg } )

                    // TODO 3.3a - call the initializeUI() function


                })
                .catch(err => {
                    console.error('Service Worker Error', err);
                });
        });
    }

As you can see, I put it in the render method of my main React component

François LG
  • 63
  • 1
  • 6
  • Doesn't make sense doing this in render() and you should never directly assign values to `state` – charlietfl Jul 10 '19 at 12:50
  • I have replaced the this.state by this.setState, and I still have the same error. Where can I put my script for registering service workers if I want it to be done automatically ? – François LG Jul 10 '19 at 12:54
  • Possible duplicate of this question https://stackoverflow.com/questions/49566059/service-worker-registration-error-unsupported-mime-type-text-html – SLCH000 Jul 11 '19 at 05:19

0 Answers0