Services Plugins FAQs

[FCM] Notification not shown

hi

I’m using your Firebase Cloud Messaging plugin. I managed to get user FCM token and use it to send request to FCM to show notification, but no notification is shown. I solved plugin configuration problems I had earlier on so it seems that it’s configured properly.

Here’s the configuration of the workflow that sends request to FCM

I put the following code in html header to store user FCM token

<script src="https://www.gstatic.com/firebasejs/10.14.0/firebase-app-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/10.14.0/firebase-messaging-compat.js"></script>

<script>
  function sendTokenToBubble(token) {
    console.log('sending token', token);
    fetch('https://aartst.bubbleapps.io/version-test/api/1.1/wf/store', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ token: token })
    });
    fetch('https://aartst.bubbleapps.io/api/1.1/wf/store', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ token: token })
    });
  }
  
  const firebaseConfig = {
    apiKey: "api key",
    authDomain: "projectId.firebaseapp.com",
    projectId: "projectId",
    storageBucket: "projectId.appspot.com",
    messagingSenderId: "some id",
    appId: "app id"
  };

  firebase.initializeApp(firebaseConfig);

  const messaging = firebase.messaging();

  // Register service worker
  navigator.serviceWorker.register('/firebase-messaging-sw-custom.js')
    .then((registration) => {
      console.log('Service Worker registered with scope:', registration.scope);

        // Request permission for notifications using the Notification API
        Notification.requestPermission()
            .then((permission) => {
                if (permission === 'granted') {
                    console.log('Notification permission granted.');

                    // Get Firebase Cloud Messaging token
                    messaging.getToken({vapidKey: 'vapid key'})
                        .then((token) => {
                            if (token) {
                                sendTokenToBubble(token);
                            } else {
                                console.log('No registration token available.');
                            }
                        })
                        .catch((err) => {
                            console.log('An error occurred while retrieving the token.', err);
                        });
                } else {
                    console.log('Unable to get permission to notify.');
                }
            })
            .catch((err) => {
                console.log('Error occurred while requesting permission', err);
            });
    })
      .catch((err) => {
          console.error('Service worker registration failed', err);
      });
  
  navigator.serviceWorker.getRegistration('/firebase-messaging-sw-custom.js')
  .then((registration) => {
    if (registration) {
      registration.unregister().then((success) => {
        if (success) {
          console.log("Firebase Messaging Service Worker unregistered.");
        }
      });
    } else {
      console.log("No matching service worker found.");
    }
  });
</script>

and service worker file

// Import Firebase scripts using the correct version (compat)
importScripts('https://www.gstatic.com/firebasejs/10.14.0/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/10.14.0/firebase-messaging-compat.js');

// Initialize Firebase
const firebaseConfig = {
  same data as in html header
};

// Initialize Firebase in the service worker
firebase.initializeApp(firebaseConfig);

// Retrieve an instance of Firebase Messaging so that it can handle background messages.
const messaging = firebase.messaging();

// Handle background messages
messaging.onBackgroundMessage((payload) => {
  console.log('Received background message: ', payload);
  const notificationTitle = payload.notification.title;
  const notificationOptions = {
    body: payload.notification.body,
    icon: 'YOUR_ICON_URL'  // Optional: Path to an icon for the notification
  };

  // Show the notification
  self.registration.showNotification(notificationTitle, notificationOptions);
});

There are no errors in the console. I also removed the above custom code from my bubble app, unregistered workers and triggerred the workflow again, but still no notification is received

Hi @aart.st ,

Thanks for reaching out! It looks like you’ve done a great job setting up everything, but there are a few common issues we can check to make sure your notifications are working properly.

1. Verify FCM Token Storage

  • Ensure that the FCM token is correctly stored in your Bubble app’s database. You’ll need to confirm that the token is being properly saved and retrieved in your workflow for sending the notification.

2. Check Firebase Configuration

  • Double-check that the Project ID and FCM Token in your workflow are correctly set up. Make sure the FCM Token is being mapped to the correct token stored in your app to target the specific user.

3. Permissions for Notifications

  • Verify that the user has granted permission for notifications. Sometimes, notifications might not appear if the permission is not granted. Ensure the user is prompted and the permission is accepted.

4. Service Worker Registration

  • Make sure your service worker is properly registered and activated. If you’re not seeing notifications, it’s worth checking your browser’s Service Workers section in DevTools to confirm that everything is running as expected.

5. Test Notification Directly from Firebase

  • To isolate the issue, try sending a test notification directly from the Firebase Console using the stored FCM token. This can help confirm if the issue is on the Firebase side or in your app’s integration.

6. Debug Workflow Triggers

  • Ensure that your workflow is correctly triggering the Send Notification action and that all necessary data (like message body, title, etc.) is passed properly.

General Tips:

  • Console Logs: Add console.log statements in both your front-end and service worker scripts to check what’s happening at each stage of the process.
  • Testing Across Devices: Be sure to test on different devices and browsers to ensure push notifications are functioning properly in all environments.

If these steps don’t resolve the issue or you need additional help, feel free to reach out again.

Best regards,
Support Team
Browse all Zeroqode Plugins for Bubble
Banner_Last3

I added

messaging.onMessage((payload) => {
    console.log('Message received. ', payload);
  });

to the html <script>...</script> and I can see in console:

{
    "from": "...",
    "messageId": "1cb7f8f0-76f5-48d0-92b8-28d524fec686",
    "notification": {
        "title": "test",
        "body": "test"
    }
}

so everything seems to be configured correctly. Both site permissions and console log show that notification permission was granted. But still no notification is displayed

ok, this code makes it work

messaging.onMessage((payload) => {
    console.log('Message received. ', payload);

      // Extract notification details from the payload
      const notificationTitle = payload.notification.title;
      const notificationOptions = {
        body: payload.notification.body,
        icon: payload.notification.icon // Optional: Path to an icon for the notification
      };

      // Show the notification
      if (Notification.permission === 'granted') {
        new Notification(notificationTitle, notificationOptions);
      }
  });

I though that your plugin will handle showing the notification

another problem - when I run action to send notification from frontend I’m getting error in server logs:
Workflow error - The service FCM - send notification to user just returned an error (HTTP 401). Please consult their documentation to ensure your call is setup properly. Raw error: { “error”: { “code”: 401, “message”: "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential …

Hi @aart.st,

Thanks for your update and for sharing your findings. It’s great to see that you were able to get the notification working by handling it manually in your script.

Regarding your expectation that the plugin should handle displaying notifications automatically—you’re correct that this would be ideal. However, browser-based push notifications often require explicit handling on the front end, which is why manually triggering new Notification(...) inside messaging.onMessage() was necessary in your case. We’ll take this into account for potential improvements to the plugin in the future.

Now, about the 401 authentication error when sending a notification from the frontend—this usually happens due to missing or incorrect credentials. Here are a few things to check:

  1. Ensure You Are Using a Valid Server Key
  • When sending push notifications from your backend, Firebase requires a valid Server Key (not the VAPID key or API key).
  • You can find this in your Firebase Console under Project Settings > Cloud Messaging > Server Key.
  • In your Bubble workflow, make sure this key is correctly set in the plugin settings or the API request.
  1. Check That Your API Request Includes the Authorization Header
  • The request to Firebase should include an Authorization header with the Bearer token (your Server Key).
  • If using the plugin’s action, ensure that the authentication is properly configured within Bubble’s API settings.
  1. Use the Correct FCM Endpoint
  • Ensure the request is being sent to https://fcm.googleapis.com/v1/projects/YOUR_PROJECT_ID/messages:send.
  • If you’re using the legacy API (https://fcm.googleapis.com/fcm/send), ensure you’re following the correct authentication method for that version.

Next Steps:

  1. Double-check that you’re using the correct Server Key (not an API key or VAPID key).
  2. Ensure the authorization header is correctly set in your API request.
  3. If the issue persists, try sending a test notification from Postman or cURL using your Server Key to confirm if authentication is working outside of Bubble.

Let me know if you need further assistance!

Best regards,
Support Team
Browse all Zeroqode Plugins for Bubble
Banner_Last3