Utilizing Firebase Cloud Messaging for push notifications in Twilio Conversations

I am currently facing a challenge in setting up push notifications using Twilio Conversations and Firebase Cloud Messaging on a Next.js 12 app. The documentation assumes the use of Firebase 8 syntax, but I am working with Firebase 9 in this case. I have been encountering difficulties in getting push notifications to display while the page is open. Even though I have set up the service worker as per Firebase docs, it does not seem to recognize when a new message is received from Twilio to show the notification.

Here are the docs I have followed:

What I've attempted

On the backend, I include the Push Credential SID when constructing a new ChatGrant:

const chatGrant = new ChatGrant({
  pushCredentialSid: process.env.TWILIO_PUSH_CREDENTIAL_SID,
  serviceSid: CONVERSATIONS_SID
});

In the frontend, I followed the Twilio documentation for Firebase setup:

init.ts

import { getMessaging, getToken, onMessage } from "firebase/messaging";
import { initializeApp } from "firebase/app";
import { Client } from "@twilio/conversations";

// Code omitted
const firebaseConfig = {};

export function getPermission(client: Client) {
  const app = initializeApp(firebaseConfig);
  const messaging = getMessaging(app);
  getToken(messaging, { vapidKey:"KEY" })
    .then((data) => {
      console.log({ data });
      client.setPushRegistrationId("fcm", data).catch((error) => {
        console.error({ error });
      });
      onMessage(messaging, (payload) => {
        console.log({ payload });
        client.handlePushNotification(payload).catch((error) => {
          console.error(error);
          // test
        });
      });
    })
    .catch((error) => {
      console.error(error);
      // test
    });
}

I invoke getPermission from this file once the conversation app loads.

  // chatClient is stored in a ref so it doesn't recalculate/refetch/reauthorize all the time
  const chatClient = useRef(null);
  // [Other code]
  chatClient.current = new ConversationClient(data.chatAccessToken);
  chatClient.current.on("connectionStateChanged", async (state) => {
    switch (state) {
      case "connected": {
        // Only get permission once the chat client is fully set up
        getPermission(chatClient.current);
        // ..........

Regarding my service worker firebase-messaging-sw.js:

importScripts('https://www.gstatic.com/firebasejs/9.14.0/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/9.14.0/firebase-messaging-compat.js');

if (!firebase.apps.length) {
  firebase.initializeApp({
    // CONFIG GOES HERE
  });
}

const messaging = firebase.messaging();

//background notifications will be received here
messaging.onBackgroundMessage(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: '/android-chrome-192x192.png'
  };

  self.registration.showNotification(notificationTitle, notificationOptions);
});

Current Situation

  • The messaging.onBackgroundMessage event in the service worker does not appear to be triggered. I am unsure of the root cause - whether Twilio is failing to pass message information to Firebase or if Firebase is not properly listening when Twilio sends the data. Could there have been changes from version 8 to 9 that are affecting this?
  • In init.ts, the onMessage method is also not being invoked. Similarly, I am uncertain if Twilio is sending the correct information to Firebase or if I missed configuring something.

No console errors or warnings are displayed, and the network tab doesn't provide much insight either.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Reveal and conceal information with a customized web address

I have a PHP and MySQL blog that I want to display in a div using show and hide JavaScript functions. Everything works fine with other divs, but the issue arises when clicking on a vanity URL causing my webpage to refresh every time it's clicked. The ...

Encountering an anomaly in persistent redux while using NEXT.JS

I recently made some updates to my ecommerce store, including adding login and register options. To ensure that user tokens are saved even after a page refresh, I decided to implement redux-persist. However, I encountered an issue where the design breaks a ...

Ways to conceal the scroll bar upon the initial loading of a webpage

Recently, I created a single-page website consisting of 4 sections. The client has specific requirements that need to be fulfilled: The scrollbar should not be visible when the page loads. Once the user starts scrolling past the second section, the scrol ...

Here's a guide on making a GET request to the Open AI API using Next.js 14

I'm attempting to send a basic GET request to the OpenAI GPT API using Next.js 14 and then simply show the results in the console, but I am encountering this error: Failed to parse URL from /api/codelang Below is the code snippet from app/test/page.j ...

Transforming Poloniex API Callback JSON into a compatible format for Highcharts.Stockchart

I am currently working on a project that involves retrieving JSON data from Poloniex's public API method (specifically the returnChartData method) to generate a graph using Highchart Stockchart. The graph would display the historical performance of va ...

Ways to display multiple PHP pages in a single division

Within my project, I have a unique setup involving three distinct PHP pages. The first file contains two divisions - one for hyperlinked URLs and the other for displaying the output of the clicked URL. Here is an excerpt from the code snippet: <script& ...

Obtain information from a website, then initiate a lambda function to send an email and store the data in

As a beginner, I came across two different sets of instructions online. The first one was about using AWS Lambda to send data (Contact us - Email, Phone, etc) to my email via Amazon API Gateway and Amazon SES: https://aws.amazon.com/blogs/architecture/cre ...

Changing the text color in a React Native TouchableHighlight component

How does TouchableHighlight change the text color when tapped? I have already configured the backgroundColor using underLayColor. Here is my updated code snippet: <TouchableHighlight style={{ borderRadius: 5}} ...

Switch up the color of the following-mouse-div in real-time to perfectly complement the color that lies underneath it

I am trying to create a div that changes color based on the complementary color of whatever is underneath the mouse pointer. I want it to follow the mouse and dynamically adjust its color. This functionality is similar to what Gpick does: https://www.you ...

Navigating through various features in nodejs / expressjs

Managing multiple functions in nodejs/expressjs can be a bit confusing for those used to PHP. In PHP, you simply call one function after another, but in node, things work differently with callbacks and potential errors related to undefined variables. Her ...

Instead of presenting MySQL data in tables on an HTML page, showcase it in editable text boxes

I have successfully imported data from my database table into an HTML table, but now I want to display them in locked text boxes. When the user clicks an "edit" button, the corresponding text box should become unlocked so that they can edit the data and sa ...

Combining two lists in immutable.js by flattening and zipping

When faced with two immutable lists, such as: const x = [5,6,7]; const y = [x,y,z,w]; Is there a straightforward method to combine/interleave them in order to obtain: const z = [5,x,6,y,7,z,w]; ...

Pressing the button does not switch the component state (when the button and component are located in separate files)

Here is the code snippet of my layout: import Menu from "./Menu"; import ButtonMenu from "./ButtonMenu"; export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <html lang="en" ...

Avoid clicking in areas outside the perimeter of the blue circle in the SVG

Is there a way to restrict clicking outside the blue circle? The goal is to only allow opening by clicking on the svg itself, This includes everything, even white space inside the svg. How can this be achieved in the code? The current behavior is that ...

What could be causing the issue with my code where the canvas is not showing boxes beyond a y-coordinate of 8 along the x-axis?

I've been working on creating a 64 square checkerboard using the html canvas element in javascript, but I'm encountering an issue. The boxes aren't rendering properly after the first 8 squares on the y-axis, and I can't figure out where ...

Preventing Past Dates from Being Selected in JQuery Date Picker

Need help with a date picker that only allows selection of the 1st and 15th dates of each month. How can I prevent users from selecting previous dates? <link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" ty ...

Question about React.js: What is the best way to add multiple classes to a component by using a ternary operator?

I am looking to apply multiple classes to a component by utilizing a ternary operator. In our shared ts theme file, we have the general button styles defined, but for this specific component, I want to adjust the sizes based on screen width. To achieve thi ...

Constantly showing blank white pages on my website specifically in Internet Explorer 11

I successfully developed a website using react, babel, webpack, and backend Django framework. Everything runs smoothly on Chrome, Safari, and Firefox, but when it comes to IE11, issues arise. Initially, the site functions properly, but after navigating thr ...

AngularJS is incapable of detaching forms from objects

Creating forms dynamically using ng-repeat and adding them to the vm.forms object is causing issues. When an item is removed from the array, the corresponding form is deleted but the key in the vm.forms object remains, leading to undefined errors. angul ...

Attempting to crack the code within body-parser and Node.js

I am just getting started with Node.js & Express and trying to follow a tutorial at https://github.com/jw84/messenger-bot-tutorial. I have a good understanding of most parts, but I'm confused about the use of "entry" and "messaging" in this code snipp ...