Experiencing a snag with implementing Firebase version 9 FCM in Next.js 12

I decided to incorporate push notifications into my Next.js (version 12) app, so I integrated Firebase Cloud Messaging. Here is the implementation:

import { initializeApp, getApp, getApps } from "firebase/app"
import { getMessaging, getToken } from "firebase/messaging"
import { firebaseConfig } from "./config"

const app = !getApps.length ? initializeApp(firebaseConfig) : getApp()

I also added the cloudMessaging function to retrieve the FCM token and the onMessageListener function to display foreground messages.

export const cloudMessaging = async () => {
  const token = await isTokenAvailable()
  if (token !== null) {
    return Promise.resolve({
      status: true,
      token: token,
    })
  }
  try {
    const permission = await Notification.requestPermission()

    const messaging = getMessaging(app)
    console.log(messaging)
    console.log(permission)
    if (permission === "granted") {
      const FCM_TOKEN = await getToken(messaging, {
        vapidKey: process.env.NEXT_PUBLIC_FCM_VAPID_KEY,
      })
      if (FCM_TOKEN) {
        localStorage.setItem("fcm_token_prac", FCM_TOKEN)
        return Promise.resolve({
          status: true,
          token: FCM_TOKEN,
        })
      }
    }
  } catch (err) {
    console.log(err, "cloudmessaging error")
    return Promise.resolve({
      status: false,
    })
  }
}
export const onMessageListener = () => {
  const messaging = getMessaging(app)
  console.log(messaging)

  return new Promise((res) => {
    messaging.onMessage((payload) => {
      res(payload)
    })
  })
}

These functions are invoked from my Layout component.

useEffect(() => {
    firebaseInit()
    async function firebaseInit() {
      try {
        await cloudMessaging()
      } catch (err) {
        console.log(err)
      }
    }
  }, [])

  useEffect(() => {
    onMessageListener()
      .then((payload) => {
        console.log(payload, "onMessageListener")
      })
      .catch((err) => console.log(err, "onMessageListener useEffect"))
  }, [])

However, I encountered this error in my console:

 TypeError: messaging.onMessage is not a function
    at eval (firbase.js?100f:58:15)
    at new Promise (<anonymous>)
    at onMessageListener (firbase.js?100f:57:10)
    at eval (Layout.js?4f8d:33:22)
    at commitHookEffectListMount (react-dom.development.js?ac89:23049:1)

I am struggling to identify where I went wrong. Can someone assist me in rectifying this?

Answer №1

One possible solution is to include onMessage in the import section.

import { getMessaging, getToken, onMessage } from "firebase/messaging"

Delete messaging from the line

messaging.onMessage

will be revised to

onMessage((payload) => {
    res(payload)
})

This adjustment is specific for SDK version 9

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

Unable to display the Error 404 Component within a nested Component using React Router

When attempting to display the Error component if no matches are found, I encountered an issue - selecting a non-existing route only leads to a blank page. In the example, the Main component adds a sidebar menu and renders all its children inside it. If ...

Escaping double quotes in dynamic string content in Javascript can prevent unexpected identifier errors

Need help with binding the login user's name from a portal to a JavaScript variable. The user's name sometimes contains either single or double quotes. I am facing an issue where my JavaScript code is unable to read strings with double quotes. ...

Why is the scroll-to-top feature not functioning properly in Next.js Link when I switch routes?

My issue involves the next/link feature where the scroll to top functionality is not working when I change routes. <Link href="/some-page" scroll={false}> Go</Link> Does anyone know how to fix this problem? I have tried several metho ...

Strengthening JavaScript Security

Throughout the past few years, I have delved into various javascript libraries like Raphael.js and D3, experimenting with animations sourced from different corners of the internet for my own learning. I've obtained code snippets from Git repositories ...

Utilize jQuery to showcase images on your webpage

There seems to be an issue with image display - sometimes the selected image does not show up until clicked a second time. Using jQuery $('#morefiles').change(function (event) { if (!(/\.(gif|jpg|jpeg|tiff|png)$/i).test($(this).val())) { ...

Access files directly through our convenient file storage site

I'm currently delving into the world of angular JS, and I've come across $https. I was looking to upload a file called db.php which includes: { "vcRecords": [ {"name":"Madison" ,"nickName":"Madilove" ,"coderType":"Injection / Fortre ...

Steps to set up gapi-script authentication with next-auth in a Next.js application

I have encountered an issue while working on my open-source project that involves utilizing the Google Drive API. Can anyone guide me on how to set up gapi-script authentication using next-auth in a Next.js project? I have managed to implement authentica ...

There is no response provided by the function

Here is the code for inserting data into the database. However, it seems to be going into the else section as the response is empty. I have checked by alerting the response, but it remains empty. // Function to add donation via AJAX function ccjkfound ...

Populate Jquery datatables programmatically

After implementing the Jquery Datatables plugin, I initially had hardcoded content in the table. However, I made some modifications to dynamically populate the table with fetched data. While this change worked fine, I encountered issues with the search f ...

Tips for using Jquery to round up currency values

Is there a way to round up various currencies using jQuery? I have a specific requirement: 10.30 → 10 //Round down if below .5 10.60 → 11 //Round up if after .5 849.95 → 850 1,022.20 → 1022 ...

Tips for efficiently populating a MongoDB database for end-to-end testing

After following the setup process outlined in this guide: https://medium.com/developer-circles-lusaka/how-to-write-an-express-js-server-using-test-driven-development-921dc55aec07, I have configured my environments accordingly. Utilizing the config package ...

Encountering a peculiar error while attempting to install firebase-tools

Currently in the process of deploying my application on Firebase by following a tutorial. I encountered an issue after executing the command npm install -g firebase-tools: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" d ...

A tutorial on how to create the appearance of disabled buttons that look the same as enabled buttons through the use

My button includes a text field that is constantly disabled. I would like for the text field to appear as bright as it does when the button is enabled. After disabling the button, they both appear dimmer compared to others and the text field follows suit ...

Refreshing jQuery via Ajax Response

In our JSF2 application, we encounter situations where we need to re-invoke the JavaScript (specifically jQuery for UI styling) when making Ajax calls. However, it seems that the JavaScript functions are not being called upon receiving the Ajax response fr ...

Do you know the method to make a Youtube iframe go fullscreen?

I am encountering an issue with developing an iframe where I am unable to make it go fullscreen from within the iframe. Fullscreen API works when both the iframe and hosting website are on the same domain, as well as triggering fullscreen from outside the ...

Encountering difficulties linking to a stylesheet or a script in an HTML file delivered by Express server

Currently, I'm facing the challenge of breaking down my Express app code into multiple files. Unfortunately, I am unable to utilize <link href> or <script src> for linking stylesheets or scripts. Below is the relevant snippet from my inde ...

Exiting a void method in JavaScript/Typescript using the return or break statement

I find myself dealing with a complex method in Typescript that contains multiple if else if else constructs. It's a void method, and I'm wondering how I can exit the method based on a specific if condition without having to execute the remaining ...

Using dynamic imports in Next.js allows us to efficiently load modules based on variables defining the path

When utilizing dynamic import in Next.js, I am encountering an issue. The component renders successfully when the path is used directly, but fails to render when the path is accessed from a variable. const faq = dynamic(() => import('../faq/faq&apo ...

When a user clicks on a button, AJAX and jQuery work together to initiate a setInterval function that continually

Currently, I have two scripts in place. The first script is responsible for fetching a specific set of child nodes from an XML file through AJAX and using them to create a menu displayed as a list of buttons within #loadMe. What's remarkable about thi ...

Creating a well-aligned form using Material-UI

Exploring Material-UI for the first time! How can a form be built where certain fields are arranged horizontally, others stacked vertically, and all aligned perfectly both vertically and horizontally? Check out this example image: I've created simila ...