Firebase FCM React project issue - firebase-messaging-sw.js wrong type?

If you are using create-react-app. Add firebase-messaging-sw.js to your public folder and rebuild. firebase-messaging-sw.js can be an empty file


If you are using firebase, react and you scaffold with create react app things you need to do:

  • create (or move) a file in the public folder name it firebase-messaging-sw-.js
    • this issue is because the default route is your root folder, but since the scaffolder uses webpack you can't put the simple file in your root folder, it got to be placed in your public folder or do some config in your webpack dev server to be able to load that file from a different route
  • register your service worker and associate that file with firebase
  • you can do this in the index file (bootstrap)
  • Check that your service worker has been registered in your browser
  • for chrome you go to Devtools > Application > ServiceWorker and check yours is register
    • if you have any issue delete you service worker and register it again

(based on @Humble Student answer)

if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('../firebase-messaging-sw.js')
    .then(function(registration) {
        firebase.messaging().useServiceWorker(registration);
    }).catch(function(err) {
      console.log('Service worker registration failed, error:', err);
    });
  }

Hope that helps!


For those using create-react-app, you can create the firebase-messaging-sw.js inside public folder and, on index.js add:

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('../firebase-messaging-sw.js')
  .then(function(registration) {
    console.log('Registration successful, scope is:', registration.scope);
  }).catch(function(err) {
    console.log('Service worker registration failed, error:', err);
  });
}

In order to receive messages, you will need to create a file called firebase-messaging-sw.js. See the section Handle messages when your web app is in the foreground in the Firebase documentation:

In order to receive the onMessage event, your app must define the Firebase messaging service worker in firebase-messaging-sw.js.