javascriptreactjsexpressservice-workercreate-react-app

Service Worker registration error: Unsupported MIME type ('text/html')


I'm using create-react-app with an express server.

create-react-app has a pre-configured ServiceWorker that caches local assets (https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#making-a-progressive-web-app).

The problem I encountered when I tried to publish on my server is that the service-worker.js file was available, but I was getting errors in my browser console when it tried to register it.

On Firefox, I got this error:

Error during service worker registration:

TypeError: ServiceWorker script at https://example.com/service-worker.js for scope https://example.com/ encountered an error during installation.

On Chrome, I get the more descriptive error:

Error during service worker registration: DOMException: Failed to register a ServiceWorker: The script has an unsupported MIME type ('text/html').

Sure enough, if I look in the Network tab of my developer tools and search for the service-worker.js file, I can see that it has the wrong MIME type in the HTTP headers.

I could not understand, though, why it has the wrong MIME type?


Solution

  • Applying this change:

    '/service-worker.js'  // ❌
    './service-worker.js' // ✅
    

    fixed my issue.

    (in navigator.serviceWorker.register('/service-worker.js'))


    Or maybe you need:

    '%PUBLIC_URL%/serviceworker.js'
    

    Thank @DanielLord for his comment.