title: Failed to register a ServiceWorker for scope ('https://.xxx.net/firebase-cloud-messaging-push-scope')
body: <p>I want to send Firebase web notifications from FCM to PWA app. I tried doing that and ended up with the below error.</p>
  
  <p>I've gone through sever links in StackOverflow but no luck.</p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/52784051/firebase-web-push-notification-service-worker-issue">Firebase web push notification Service worker issue</a></li>
  <li><a href="https://stackoverflow.com/questions/52740611/firebaseerror-messaging-we-are-unable-to-register-the-default-service-worker">FirebaseError: Messaging: We are unable to register the default service worker</a></li>
  </ul>
  
  <pre class="lang-none prettyprint-override"><code>A bad HTTP response code (404) was received when fetching the script.
  
  An error occurred while retrieving token. FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('https://dms-uat.xxxxxx.net/firebase-cloud-messaging-push-scope') with script ('https://dms-uat.xxxxxx.net/firebase-messaging-sw.js'): A bad HTTP response code (404) was received when fetching the script. (messaging/failed-service-worker-registration).
  at rt. (https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js:1:31316)
  at https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js:1:1935
  at Object.throw (https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js:1:2040)
  at i (https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js:1:834)
  </code></pre>
  
  <p>Both <code>index.html</code> and <code>firebase-messaging-sw.js</code> files are currently in the <code>domain/messaging</code> folder.</p>
  
  <p>I was taught that <code>firebase-messaging-sw.js</code> file should be in the root folder which means <code>domain/firebase-messaging-sw.js</code>, is this correct? If so, how could I make it done?</p>
  
  <p>Service worker in browser:</p>
  
  <p><a href="https://i.stack.imgur.com/xOKuV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xOKuV.png" alt="service worker"></a></p>
  
  <p>Here is my firebase-messaging-sw.js file.  </p>
  
  <pre><code>// These scripts are made available when the app is served or deployed on Firebase Hosting
  // If you do not serve/host your project using Firebase Hosting see https://firebase.google.com/docs/web/setup
  importScripts('https://www.gstatic.com/firebasejs/7.14.0/firebase-app.js');
  importScripts('https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js');
  importScripts('https://www.gstatic.com/firebasejs/7.14.0/init.js');
  
  const messaging = firebase.messaging();
  
  var firebaseConfig = {
              apiKey: "xxxxxxxx-l7lKJ6nAtsmyfXRX5gXcl2_0a3Y",
              authDomain: "xxxxxx-9fa59.firebaseapp.com",
              databaseURL: "https://xxxxxx-9fa59.firebaseio.com",
              projectId: "xxxxx-9fa59",
              storageBucket: "xxxxxx-9fa59.appspot.com",
              messagingSenderId: "123456789",
              appId: "1:215883024305:web:f1b6b2148bd185584d1f90",
              measurementId: "G-MP1GQDZ18D"
          };
          // Initialize Firebase
          firebase.initializeApp(firebaseConfig);
          //firebase.analytics();
  
  
  
  /**
   * Here is is the code snippet to initialize Firebase Messaging in the Service
   * Worker when your app is not hosted on Firebase Hosting.
  
   // [START initialize_firebase_in_sw]
   // Give the service worker access to Firebase Messaging.
   // Note that you can only use Firebase Messaging here, other Firebase libraries
   // are not available in the service worker.
   importScripts('https://www.gstatic.com/firebasejs/7.14.0/firebase-app.js');
   importScripts('https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js');
  
   // Initialize the Firebase app in the service worker by passing in
   // your app's Firebase config object.
   // https://firebase.google.com/docs/web/setup#config-object
   firebase.initializeApp({
     apiKey: 'api-key',
     authDomain: 'project-id.firebaseapp.com',
     databaseURL: 'https://project-id.firebaseio.com',
     projectId: 'project-id',
     storageBucket: 'project-id.appspot.com',
     messagingSenderId: 'sender-id',
     appId: 'app-id',
     measurementId: 'G-measurement-id',
   });
  
   // Retrieve an instance of Firebase Messaging so that it can handle background
   // messages.
   const messaging = firebase.messaging();
   // [END initialize_firebase_in_sw]
   **/
  
  
  // If you would like to customize notifications that are received in the
  // background (Web app is closed or not in browser focus) then you should
  // implement this optional method.
  // [START background_handler]
  messaging.setBackgroundMessageHandler(function(payload) {
    console.log('[firebase-messaging-sw.js] Received background message ', payload);
    // Customize notification here
    const notificationTitle = 'Background Message Title';
    const notificationOptions = {
      body: 'Background Message body.',
      icon: './firebase-logo.png'
    };
  
    return self.registration.showNotification(notificationTitle,
      notificationOptions);
  });
  // [END background_handler]
  </code></pre>
  
  <p>Here is my index.html </p>
  
  <pre><code>&lt;!--
  Copyright (c) 2016 Google Inc.
  
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
  
  http://www.apache.org/licenses/LICENSE-2.0
  
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  --&gt;
  &lt;html&gt;
  &lt;head&gt;
  &lt;meta charset=utf-8 /&gt;
  &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
  &lt;title&gt;Firebase Cloud Messaging Example&lt;/title&gt;
  
  &lt;!-- Material Design Theming --&gt;
  &lt;link rel="stylesheet" href="https://code.getmdl.io/1.1.3/material.orange-indigo.min.css"&gt;
  &lt;link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"&gt;
  &lt;script defer src="https://code.getmdl.io/1.1.3/material.min.js"&gt;&lt;/script&gt;
  
  &lt;link rel="stylesheet" href="./main.css"&gt;
  
  &lt;link rel="manifest" href="./manifest.json"&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;div class="demo-layout mdl-layout mdl-js-layout mdl-layout--fixed-header"&gt;
  
        &lt;!-- Header section containing title --&gt;
        &lt;header class="mdl-layout__header mdl-color-text--white mdl-color--light-blue-700"&gt;
            &lt;div class="mdl-cell mdl-cell--12-col mdl-cell--12-col-tablet mdl-grid"&gt;
                &lt;div class="mdl-layout__header-row mdl-cell mdl-cell--12-col mdl-cell--12-col-tablet mdl-cell--8-col-desktop"&gt;
                    &lt;h3&gt;Firebase Cloud Messaging&lt;/h3&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/header&gt;
  
        &lt;main class="mdl-layout__content mdl-color--grey-100"&gt;
            &lt;div class="mdl-cell mdl-cell--12-col mdl-cell--12-col-tablet mdl-grid"&gt;
  
                &lt;!-- Container for the Table of content --&gt;
                &lt;div class="mdl-card mdl-shadow--2dp mdl-cell mdl-cell--12-col mdl-cell--12-col-tablet mdl-cell--12-col-desktop"&gt;
                    &lt;div class="mdl-card__supporting-text mdl-color-text--grey-600"&gt;
                        &lt;!-- div to display the generated Instance ID token --&gt;
                        &lt;div id="token_div" style="display: none;"&gt;
                            &lt;h4&gt;Instance ID Token&lt;/h4&gt;
                            &lt;p id="token" style="word-break: break-all;"&gt;&lt;/p&gt;
                            &lt;button class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored"
                                    onclick="deleteToken()"&gt;
                                Delete Token
                            &lt;/button&gt;
                        &lt;/div&gt;
                        &lt;!-- div to display the UI to allow the request for permission to
                             notify the user. This is shown if the app has not yet been
                             granted permission to notify. --&gt;
                        &lt;div id="permission_div" style="display: none;"&gt;
                            &lt;h4&gt;Needs Permission&lt;/h4&gt;
                            &lt;p id="token"&gt;&lt;/p&gt;
                            &lt;button class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored"
                                    onclick="requestPermission()"&gt;
                                Request Permission
                            &lt;/button&gt;
                        &lt;/div&gt;
                        &lt;!-- div to display messages received by this app. --&gt;
                        &lt;div id="messages"&gt;&lt;/div&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
  
            &lt;/div&gt;
        &lt;/main&gt;
    &lt;/div&gt;
  
    &lt;!-- Import and configure the Firebase SDK --&gt;
    &lt;!-- These scripts are made available when the app is served or deployed on Firebase Hosting --&gt;
    &lt;!-- If you do not serve/host your project using Firebase Hosting see https://firebase.google.com/docs/web/setup --&gt;
  
  &lt;!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services --&gt;
  
  &lt;!-- Firebase App (the core Firebase SDK) is always required and must be listed first --&gt;
  &lt;script src="https://www.gstatic.com/firebasejs/7.14.0/firebase-app.js"&gt;&lt;/script&gt;
  &lt;!-- Add Firebase products that you want to use --&gt;
  &lt;script src="https://www.gstatic.com/firebasejs/7.14.0/firebase-auth.js"&gt;&lt;/script&gt;
  &lt;!--   &lt;script src="https://www.gstatic.com/firebasejs/7.14.0/firebase-firestore.js"&gt;&lt;/script&gt;--&gt;
    &lt;script src="https://www.gstatic.com/firebasejs/7.14.0/firebase-messaging.js"&gt;&lt;/script&gt;
    &lt;!-- &lt;script src='https://cdn.firebase.com/js/client/2.2.1/firebase.js'&gt;&lt;/script&gt; --&gt;
    &lt;script&gt;
  
    var firebaseConfig = {
            apiKey: "xxxxxxxx-l7lKJ6nAtsmyfXRX5gXcl2_0a3Y",
            authDomain: "xxxxx-9fa59.firebaseapp.com",
            databaseURL: "https://xxxxx-9fa59.firebaseio.com",
            projectId: "xxxxx-9fa59",
            storageBucket: "xxxxx-9fa59.appspot.com",
            messagingSenderId: "123456789",
            appId: "1:215883024305:web:f1b6b2148bd185584d1f90",
            measurementId: "G-MP1GQDZ18D"
        };
        // Initialize Firebase
        firebase.initializeApp(firebaseConfig);
        //firebase.analytics();
  
      // [START get_messaging_object]
      // Retrieve Firebase Messaging object.
      const messaging = firebase.messaging();
      // [END get_messaging_object]
      // [START set_public_vapid_key]
      // Add the public key generated from the console here.
      messaging.usePublicVapidKey('BDTDxT_59kRHBjDTBwnDvFQcdy8Y8A8NvjFFzW2aMo27raPODdeX89pSBA6pxerBbmpBXaLxiadjiNHTDmComhs');
      // [END set_public_vapid_key]
  
      // IDs of divs that display Instance ID token UI or request permission UI.
      const tokenDivId = 'token_div';
      const permissionDivId = 'permission_div';
  
      // [START refresh_token]
      // Callback fired if Instance ID token is updated.
      messaging.onTokenRefresh(() =&gt; {
        messaging.getToken().then((refreshedToken) =&gt; {
          console.log('Token refreshed.');
          // Indicate that the new Instance ID token has not yet been sent to the
          // app server.
          setTokenSentToServer(false);
          // Send Instance ID token to app server.
          sendTokenToServer(refreshedToken);
          // [START_EXCLUDE]
          // Display new Instance ID token and clear UI of all previous messages.
          resetUI();
          // [END_EXCLUDE]
        }).catch((err) =&gt; {
          console.log('Unable to retrieve refreshed token ', err);
          showToken('Unable to retrieve refreshed token ', err);
        });
      });
      // [END refresh_token]
  
      // [START receive_message]
      // Handle incoming messages. Called when:
      // - a message is received while the app has focus
      // - the user clicks on an app notification created by a service worker
      //   `messaging.setBackgroundMessageHandler` handler.
      messaging.onMessage((payload) =&gt; {
        console.log('Message received. ', payload);
        // [START_EXCLUDE]
        // Update the UI to include the received message.
        appendMessage(payload);
        // [END_EXCLUDE]
      });
      // [END receive_message]
  
      function resetUI() {
        clearMessages();
        showToken('loading...');
        // [START get_token]
        // Get Instance ID token. Initially this makes a network call, once retrieved
        // subsequent calls to getToken will return from cache.
        messaging.getToken().then((currentToken) =&gt; {
          if (currentToken) {
            sendTokenToServer(currentToken);
            updateUIForPushEnabled(currentToken);
          } else {
            // Show permission request.
            console.log('No Instance ID token available. Request permission to generate one.');
            // Show permission UI.
            updateUIForPushPermissionRequired();
            setTokenSentToServer(false);
          }
        }).catch((err) =&gt; {
          console.log('An error occurred while retrieving token. ', err);
          showToken('Error retrieving Instance ID token. ', err);
          setTokenSentToServer(false);
        });
        // [END get_token]
      }
  
  
      function showToken(currentToken) {
        // Show token in console and UI.
        const tokenElement = document.querySelector('#token');
        tokenElement.textContent = currentToken;
      }
  
      // Send the Instance ID token your application server, so that it can:
      // - send messages back to this app
      // - subscribe/unsubscribe the token from topics
      function sendTokenToServer(currentToken) {
          if (!isTokenSentToServer()) {
              console.log('Sending token to server...' + currentToken);
          // TODO(developer): Send the current token to your server.
          setTokenSentToServer(true);
        } else {
          console.log('Token already sent to server so won\'t send it again ' +
              'unless it changes');
        }
  
      }
  
      function isTokenSentToServer() {
        return window.localStorage.getItem('sentToServer') === '1';
      }
  
      function setTokenSentToServer(sent) {
        window.localStorage.setItem('sentToServer', sent ? '1' : '0');
      }
  
      function showHideDiv(divId, show) {
        const div = document.querySelector('#' + divId);
        if (show) {
          div.style = 'display: visible';
        } else {
          div.style = 'display: none';
        }
      }
  
      function requestPermission() {
        console.log('Requesting permission...');
        // [START request_permission]
        Notification.requestPermission().then((permission) =&gt; {
          if (permission === 'granted') {
            console.log('Notification permission granted.');
            // TODO(developer): Retrieve an Instance ID token for use with FCM.
            // [START_EXCLUDE]
            // In many cases once an app has been granted notification permission,
            // it should update its UI reflecting this.
            resetUI();
            // [END_EXCLUDE]
          } else {
            console.log('Unable to get permission to notify.');
          }
        });
        // [END request_permission]
      }
  
      function deleteToken() {
        // Delete Instance ID token.
        // [START delete_token]
        messaging.getToken().then((currentToken) =&gt; {
          messaging.deleteToken(currentToken).then(() =&gt; {
            console.log('Token deleted.');
            setTokenSentToServer(false);
            // [START_EXCLUDE]
            // Once token is deleted update UI.
            resetUI();
            // [END_EXCLUDE]
          }).catch((err) =&gt; {
            console.log('Unable to delete token. ', err);
          });
          // [END delete_token]
        }).catch((err) =&gt; {
          console.log('Error retrieving Instance ID token. ', err);
          showToken('Error retrieving Instance ID token. ', err);
        });
  
      }
  
      // Add a message to the messages element.
      function appendMessage(payload) {
        const messagesElement = document.querySelector('#messages');
        const dataHeaderELement = document.createElement('h5');
        const dataElement = document.createElement('pre');
        dataElement.style = 'overflow-x:hidden;';
        dataHeaderELement.textContent = 'Received message:';
        dataElement.textContent = JSON.stringify(payload, null, 2);
        messagesElement.appendChild(dataHeaderELement);
        messagesElement.appendChild(dataElement);
      }
  
      // Clear the messages element of all children.
      function clearMessages() {
        const messagesElement = document.querySelector('#messages');
        while (messagesElement.hasChildNodes()) {
          messagesElement.removeChild(messagesElement.lastChild);
        }
      }
  
      function updateUIForPushEnabled(currentToken) {
        showHideDiv(tokenDivId, true);
        showHideDiv(permissionDivId, false);
        showToken(currentToken);
      }
  
      function updateUIForPushPermissionRequired() {
        showHideDiv(tokenDivId, false);
        showHideDiv(permissionDivId, true);
      }
  
      resetUI();
    &lt;/script&gt;
  
  
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/gB4IL.png" rel="noreferrer"><img src="https://i.stack.imgur.com/gB4IL.png" alt="Project structure"></a>
  I didn't much changes except firebase-ap.js, firebase-mesaging.js files. 
  Please let me know if you need more info. </p>