FG
💻 Software🔌 APIs & SDKsGoogle

Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker

Fresh5 days ago
Mar 14, 20260 views
Confidence Score69%
69%

Problem

Operating System MacOS Browser Version All browser Firebase SDK Version 10.2.0 Firebase SDK Product: Messaging Describe your project's tooling Nextjs 13 with Page setup. Example Repo -> https://github.com/2manoj1/nextjs-firebase-example/tree/main Describe the problem Same problem as https://github.com/firebase/firebase-js-sdk/issues/5797 Sometimes calling messaging getToken returns the error: Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker. It seems to occur on the first page load and clear storage with unregister sw, when the user refreshes the notifications work and there's no error anymore. <img width="1726" alt="Screenshot 2023-08-21 at 1 45 33 PM" src="https://github.com/firebase/firebase-js-sdk/assets/15128569/d01424c8-c42a-4786-8e63-515bcb1949aa"> Steps and code to reproduce issue - Open https://nextjs-firebase-example.vercel.app/ - Open inspect element - F12 - Clear Storage with Service Worker - Refresh the browser. - See the error. Its coming also first time

Error Output

error: Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker. 

Unverified for your environment

Select your OS to check compatibility.

1 Fix

Canonical Fix
Unverified Fix
New Fix – Awaiting Verification

Ensure Active Service Worker Before Firebase Messaging Subscription

Medium Risk

The error occurs because the Firebase Messaging SDK attempts to subscribe to push notifications before the Service Worker is fully registered and active. When the Service Worker is unregistered or not yet initialized, the PushManager cannot create a subscription, leading to the error.

Awaiting Verification

Be the first to verify this fix

  1. 1

    Register Service Worker

    Ensure that the Service Worker is registered before attempting to get the token for Firebase Messaging. This can be done in the main entry point of your application.

    javascript
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('/firebase-messaging-sw.js')
        .then((registration) => {
          console.log('Service Worker registered with scope:', registration.scope);
        })
        .catch((error) => {
          console.error('Service Worker registration failed:', error);
        });
    }
  2. 2

    Wait for Service Worker Activation

    Before calling `getToken`, ensure that the Service Worker is active. You can listen for the 'activated' event to confirm this.

    javascript
    navigator.serviceWorker.ready.then((registration) => {
      console.log('Service Worker is active:', registration.active);
      // Now it's safe to call getToken
    });
  3. 3

    Call getToken After Service Worker is Ready

    Only call the `getToken` method after confirming that the Service Worker is active. This prevents the subscription error from occurring.

    javascript
    messaging.getToken({ vapidKey: 'YOUR_PUBLIC_VAPID_KEY' })
      .then((currentToken) => {
        if (currentToken) {
          console.log('Token received:', currentToken);
        } else {
          console.warn('No registration token available. Request permission to generate one.');
        }
      })
      .catch((err) => {
        console.error('An error occurred while retrieving token. ', err);
      });
  4. 4

    Handle Service Worker Unregistration

    If the Service Worker is unregistered, ensure to re-register it and wait for it to become active before attempting to subscribe again.

    javascript
    navigator.serviceWorker.getRegistration().then((registration) => {
      if (!registration) {
        // Register the service worker again
        return navigator.serviceWorker.register('/firebase-messaging-sw.js');
      }
      return registration;
    }).then((registration) => {
      // Wait for the service worker to be ready
      return registration.ready;
    });

Validation

To confirm the fix worked, clear the browser storage and refresh the page. Check the console for successful Service Worker registration and ensure that the `getToken` method does not throw any errors. Notifications should work as expected without any subscription errors.

Sign in to verify this fix

Environment

Submitted by

AC

Alex Chen

2450 rep

Tags

firebasegooglesdkapi:-messagingquestionneeds-infono-recent-activity