Service Worker registration error: Unsupported MIME type ('text/html')
JavascriptReactjsExpressService WorkerCreate React-AppJavascript Problem Overview
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://my-domain.com/service-worker.js for scope https://my-domain.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?
Javascript Solutions
Solution 1 - Javascript
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 https://stackoverflow.com/users/5129542/daniel-lord">@DanielLord</a> for his"">https://stackoverflow.com/questions/49566059/service-worker-registration-error-unsupported-mime-type-text-html/54211500?noredirect=1#comment125423210_54211500">his comment.
Solution 2 - Javascript
In my Express server application, I have one wildcard (asterisk / *) route that redirects to index.html
:
// Load React App
// Serve HTML file for production
if (env.name === "production") {
app.get("*", function response(req, res) {
res.sendFile(path.join(__dirname, "public", "index.html"));
});
}
This is a very common design pattern. However, it means that any requests for unknown text files initially get redirected to index.html
, and therefore return with the MIME type of "text/html"
, even if it's actually a JavaScript or SVG or some other kind of plaintext file.
The solution I found was to add a specific route for service-worker.js
before the wildcard route:
app.get("/service-worker.js", (req, res) => {
res.sendFile(path.resolve(__dirname, "public", "service-worker.js"));
});
app.get("*", function response(req, res) {
res.sendFile(path.join(__dirname, "public", "index.html"));
});
Now, when the browser looks for service-worker.js
, Express will return it with the correct MIME type.
(Note that if you try adding the service-worker.js
route after the wildcard, it won't work because the wildcard route will override.)
Solution 3 - Javascript
I think that the service worker file is not present at http://localhost:3000/service-worker.js
so the server is returning index.html instead. Then the registration function has no idea of what to do with a index.html file and tells you that the MIME-type is not correct.
A quick fix would be to copy the service-worker.js file to the public
folder so that when you hit http://localhost:3000/service-worker.js
you see the file in the browser.
Remember to go to ChromeDev > Applications > ServiceWorkers and hit Unsubscribe. in order to remove the errored one. Remember also disable cache
Solution 4 - Javascript
ServiceWorker supported MIME type are 'text/javascript', application/javascript and application/x-javascript. go to your server file and set
response.writeHead(201, {
'Content-Type': 'application/javascript'
});
Solution 5 - Javascript
In case, you're working on NodeJS, serviceWorker file should place at public folder. If you're using Webpack to export serviceWorker to public, you need to use 'copy-webpack-plugin'.
Solution 6 - Javascript
I use nginx to serve react app and I resolved this issue adding mime types to nginx:
http {
include mime.types; // <--- this line
# another config details
}
Also you can find mime.types file here
Solution 7 - Javascript
React: public/index.html
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('sw-cached-site.js', function() {
navigator.serviceWorker.register('service-worker.js', {
scope: '/',
});
});
}
window.process = { env: { NODE_ENV: 'production' } };
</script>
Note: Full app/site public/sw-cached-site.js
const cacheName = 'v1';
self.addEventListener('activate', (e) =>{
e.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cache => {
if(cache !== cacheName) {
return caches.delete(cache);
}
})
)
})
)
});
self.addEventListener('fetch', e => {
e.respondWith(
fetch(e.request)
.then(res => {
const resClone = res.clone();
caches
.open(cacheName)
.then(cache => {
cache.put(e.request, resClone);
});
return res;
}).catch(err => caches.match(e.request).then(res => res))
);
});
Solution 8 - Javascript
Make sure that the service worker file is generated (Chrome DevTools -> Sources -> Filesystem). You may receive such an error if the service worker file is not generated at all (check your deployment script).
Solution 9 - Javascript
In my case, for Vue I needed to generate the mockServiceWorker.js in the public directory using the command-line tool as described here:
https://mswjs.io/docs/getting-started/integrate/browser
This was not clear from the samples to me. Specifically the CLI command to run is:
npx msw init ./public
Solution 10 - Javascript
When running webpack dev server, it renders default index.html for missing resource.
If you use your browser to load http://localhost:3000/sw.js
, you will actually see a rendered react app (started by the index.html). That's why the mime type is html, not javascript.
This fallback to index.html is designed to support SPA with front-end routes. For example /product/123/reviews
has no such html file in backend, the JS SPA app takes care of it in front-end.
Why your file is missing? I guess you created that file in the root folder of your project.
Webpack dev server doesn't serve from that root folder.
Move your sw.js into public/ folder of your project, it will be served up as expected.
Solution 11 - Javascript
The script has an unsupported MIME type ('text/html'). Failed to load resource: net::ERR_INSECURE_RESPONSE (index):1 Uncaught (in promise) DOMException: Failed to register a ServiceWorker: The script has an unsupported MIME type ('text/html').
Code for template.js root file
export default ({ markup, css }) => {
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MERN Marketplace</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:100,300,400">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<style>
a{
text-decoration: none
}
</style>
<link rel="manifest" href="./manifest.json">
</head>
<body style="margin:0">
<div id="root">${markup}</div>
<style id="jss-server-side">${css}</style>
<script type="text/javascript" src="/dist/bundle.js"></script>
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').then(function() {
console.log("Service Worker Registered");
});
}
</script>
</body>
</html>`;
};
Solution 12 - Javascript
I was facing the same issue and removing other firebase libraries from my config solve the issue for me Check this on Github
// Change this
var firebaseConfig = {
apiKey: "*********",
authDomain: "**********",
databaseURL: "*********",
projectId: "***********",
storageBucket: "************",
messagingSenderId: "***********",
appId: "************"
};
// To =>
var firebaseConfig = {
apiKey: "*****************",
projectId: "**********",
messagingSenderId: "*******",
appId: "***********"
};
Solution 13 - Javascript
I guess, service worker file should be on root path. In my case, I cannot use root path, so I redirect service-worker.js to my sub path using apache redirect rule.
RewriteRule "^/service-worker.js$" "/sub/service-worker.js"
Solution 14 - Javascript
I had similar issue when hosting a site with python. None of the solutions here worked for me and I came across a bug posted in chrome dev forum which managed to resolve my issue. Apparently it was windows related issue in my case as the registry entry for .js files had content type set to text/plain due to some previous configuration which I had to change back to application/javascript.
TLDR:
- Open Registry Editor
- Go to Computer\HKEY_CLASSES_ROOT\.js
- Change Content Type to application/javascript
- Restart Chrome and run your site
Hope this helps some one in case none of the above works.
Solution 15 - Javascript
This error is because the application (Angular in this case) don't found the file service-worker.js
(ngsw-config.js
or every else name file).
I solved the problem by adding in angular.json
:
"serviceWorker": true,
"ngswConfigPath": "service-worker.json",
This should be added to all configurations: production, testing and staging, for example.
Solution 16 - Javascript
self.addEventListener('fetch', function(event) {});
Add Above code on your service-worker.js file