What is the use of firebase-messaging-sw.js in firebase web notifications?

Create empty file firebase-messaging-sw.js at root of project.


You can use the configuration below or just the messagingSenderID. You may have setup the config in your other javascript due to which it is not throwing any error.

var config = {
        apiKey: "",
        authDomain: "",
        databaseURL: "",
        storageBucket: "",
        messagingSenderId: ""
    };

firebase-messaging-sw.js is a must and should be present in the host root directory. This is required to setup background notification handler when browser is not in focus or in background.


By default firebase will be looking for /firebase-messaging-sw.js which should contain the firebase libraries and listeners. More details here: https://firebase.google.com/docs/cloud-messaging/js/receive

If you would like to use an existing service worker, you can use https://firebase.google.com/docs/reference/js/firebase.messaging.Messaging#useServiceWorker

like this...

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