Failed to register a ServiceWorker: The script has an unsupported MIME type - reactjs

Viewed 10412

I want to add firebase to my project. but I got this error message:

FirebaseError {code: "messaging/failed-serviceworker-registration", message: "Messaging: We are unable to register the default s…). (messaging/failed-serviceworker-registration).", browserErrorMessage: "Failed to register a ServiceWorker: The script has an unsupported MIME type ('text/html').", stack: "FirebaseError: Messaging: We are unable to registe…es/@firebase/messaging/dist/index.cjs.js:1951:32)"}
browserErrorMessage: "Failed to register a ServiceWorker: The script has an unsupported MIME type ('text/html')."
code: "messaging/failed-serviceworker-registration"
message: "Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker: The script has an unsupported MIME type ('text/html'). (messaging/failed-serviceworker-registration)."
stack: "FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker: The script has an unsupported MIME type ('text/html'). (messaging/failed-serviceworker-registration).↵    at eval (webpack-internal:///./node_modules/@firebase/messaging/dist/index.cjs.js:1951:32)"
__proto__: Error

solution: I must place firebase-messaging-sw.js file inside public directory.

but on reactjs, we haven't a public directory.

enter image description here

2 Answers

If you are using react boilerplate:

I added like this:

new OfflinePlugin({
  relativePaths: false,
  publicPath: '/',
  appShell: '/',
  ServiceWorker: {
    events: true,
    entry: path.join(process.cwd(), 'app/firebase-messaging-sw.js') //<-- path for your extended service worker
  },

  // No need to cache .htaccess. See http://mxs.is/googmp,
  // this is applied before any match in `caches` section
  excludes: ['.htaccess'],

I have a push-notification.js and I should call firebase-messaging-sw.js inside it:

  navigator.serviceWorker
    .register('./firebase-messaging-sw.js')
    .then((registration) => {
      firebase.messaging().useServiceWorker(registration);
    });

two files are the same directory(app). if you get the same error,

then:

app.js
`import 'file-loader?name=firebase-messaging-sw.js!./firebase-messaging-sw.js';`

i am using react-boiler-plate which does not have public folder where we have to put the firebase-messaging-sw.js. In react-boiler-plate we have to put this code

new OfflinePlugin({
relativePaths: false,
publicPath: '/',
appShell: '/',
ServiceWorker: {
    events: true,
    entry: path.join(process.cwd(), 'app/firebase-messaging-sw.js') //<-- path for your extended service worker
},

inside

internals/webpack/webpack.prod.babel.js

and inside app.js we have to import like this

// firebase messaging
import 'file-loader?name=firebase-messaging-sw.js!./firebase-messaging-sw.js';

and it should work now :)

Related