I have a React app that works in development and in production, however in production I get the following error in the console:
The script has an unsupported MIME type ('text/html').
Failed to load resource: net::ERR_INSECURE_RESPONSE
registerServiceWorker.js:80 Error during service worker registration:
DOMException: Failed to register a ServiceWorker: The script has an unsupported MIME type ('text/html').
The error does not happen in development, only in the production environment. The app still works correctly in production, however I would still prefer to sort out the error.
After doing some digging, it seems that in production the service-worker.js
file is requested from the original index.html
file while has a MIME type of text/html
, the service-worker.js
file therefore does not have the correct MIME type which would need to be application/javascript
.
Unfortunately even though I think I understand what the issue is, I haven't been able to fix it.
The production build was created using create-react-app
and is served up by a Django
backend. The index.html
page containing the React
app is served up as follows:
re_path('.*', TemplateView.as_view(template_name='index.html'))
Is there perhaps something on Nginx
that needs changing? I would guess not since I have other production sites working correctly with respect to MIME types (however none of them are React
apps requiring service workers).
To register the service worker, navigate to the src/index.js file, and look for the following line: Change it to the following line. This single line change will now enable you to use service workers in your React application. In a general web application, you would have to code the whole lifecycle of a service worker.
by the way, the mime type error happens before the service worker has a chance to register (or even load its module code) - it is thrown because the server is not set up to serve this path/uri pattern, or due security restrictions in the client.
The script has an unsupported MIME type ('text/html'). Register a Service Worker in React (change from unregister to register, or place SW code directly in index.html, or use a simpler SW.
The lifecycle of a service worker typically needs to be coded by the developer. In case of service workers in React, the life cycle management is handled by React itself, which makes the process easier for a developer to enable and use service workers.
It happens if you have registered some service workers. If you open Chrome developer tools you may get some errors. Go to
Chrome Dev Tools -> Application -> Service Worker
In there if you are seeing some service worker is registered then you have to unregister it by clicking it and after that refresh the page and check.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With