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

What is the process for applying the source from an object while utilizing video-js?

I've been struggling to use a video player for streaming m3u8 videos. The code below works, but I want to dynamically set the source using an object. <video id="my-video" class="video-js" auto ...

The deletion was not successfully carried out in the ajax request

Can anyone help with an issue I'm having while trying to remove a row from a table using the closest function? The function works fine outside of the $.post request, but it doesn't work properly when used within the post request. Here is my code: ...

Looking to trigger the closing of a q-popup-proxy by clicking a button from a separate component

I am currently working with a q-popup-proxy component in my project. <q-btn label="Add Fault" class="addFaultButton" dense @click="openPopUp()"> <q-popup-proxy position="center" v-if="openFaults" ...

Having trouble retrieving JSON data from an external source

I'm currently facing a challenge where I am unable to fetch JSON data from a webpage despite multiple attempts. I keep encountering the following errors: Uncaught SyntaxError: Unexpected token : or XMLHttpRequest cannot load URL. No 'Access-Co ...

Enabling individuals to transfer their content to Amazon S3

I have set up an S3 bucket named BUCKET in region BUCKET_REGION. I want to enable users of my web and mobile apps to upload image files to this bucket, with specific restrictions based on Content-Type and Content-Length (specifically, only allowing jpegs u ...

Detecting Whether a Vue/Vue Router Navigation was Triggered by the Back/Forward Button or a Manual Router Push

When using vue/vue-router, I have set up a watcher on $route that is triggered in two different ways: By clicking back or forward on the browser. When the user interacts with a form. There are watchers on the variables that the form uses, and these watch ...

The functionality of using multiple inputs with Google Places API is not functioning as expected

Having trouble with the Google Place API. I am unable to set up 2 input fields with autocomplete. The first input is populated from a payload received from the backend, while the second input is within a Bootstrap modal. I have tried various solutions fou ...

Using curly brackets as function parameters

Can someone help me understand how to pass an emailID as a second parameter in curly braces as a function parameter and then access it in AccountMenuSidebar? I apologize for asking such a basic question, I am new to JavaScript and React. class Invoices ex ...

No instances are returned by Processing.instances

I am experiencing an issue with a webpage that is running 2 processing sketches. I came across a suggestion to call Processing.instances[0].exit() in response to a question on dynamically unloading a Processing JS sketch from canvas. However, when I attem ...

Incorporate JSON information into HTML dropdown menu using Google API

I'm finding it difficult with this task. Below is a list that needs the name and address inserted into the dropdown menu from the JSON file. <div class="dropdown-list"> <div class="list-container"> <ul class="list" ...

Encountering difficulties when attempting to store files using mongoose in a node express.js program

I encountered an error while attempting to save a document to the MongoDB using Mongoose in my Node Express.js project. Below is the code snippet: exports.storeJob = async (req, res, next) => { const { name, email, password, title, location, descri ...

Expanding the width of a Datatables within a Bootstrap modal

While working on my modal, I encountered an issue with the width of Datatables. Despite trying to adjust it to fit the modal size, it appears like this: Below is the jQuery code calling the Datatables: function retrieveTags(){ var identifier = $(&a ...

Using ng-repeat to iterate over forms in AngularJS

I have implemented dynamic forms using the ng-repeat directive where form fields are generated based on the userid value. The requirement is that the add user button should be enabled only when all form fields are filled. However, currently the button rema ...

React code to automatically scroll to the top of the page when the user clicks the

Whenever the URL changes or the page is reloaded in my project, I need it to scroll back to the top. While most scenarios work fine, I'm encountering an issue with the browser's back button. Despite a change in the pathname, the page fails to scr ...

Angular 10 and Typescript: Variables assigned within the change event become undefined

In my code, I initialize an Algolia input and set an onchange event to it. This initialization takes place in a service. algolia_data; random_var; this.http.post<any>('APIENDPOINT', formData).subscribe(data => { instance = places({ ...

Discovering the right row to input the data and successfully integrating it: What is the best

Below is the code I am using to add a new task: <fieldset> <legend>Create New Task</legend> <input type="text" ng-model="subtaskname" placeholder="Subtask Name" ><br /> <select id="s1" ng-model="selectedItem" ng-options=" ...

The performance of the Ajax Jquery remove function leaves something to be desired

My table has items with a delete button for each row. To achieve this, I created the following Ajax function: $(document).ready(function() { $(".destroy-device").click(function(e) { e.preventDefault(); var id = $(this).attr("data-id"); $.aj ...

Storing uploaded files with multer in a Node.js environment using JavaScript

I am facing an issue with uploading multi part form data containing one file input and several text inputs. I have a directory named 'public' which contains a sub-directory named 'uploads'. My goal is to store all multer uploads in the ...

Having trouble locating my images in a project created with Webpack-simple and Vuejs using vue-cli

My folder structure looks like this: Since my website is simple, I prefer using just a json file to feed data instead of requiring an administrator. In my Cases.vue file, I have a v-for loop that iterates through my data/cases.json file, but I'm hav ...

Struggling with adding documents into mongoDB with the help of mongoose and node.js

I have a mongoose model defined below: module.exports = mongoose.model('vbDetail', { company_name: String, rowsdata: {vals: { date: Date, transaction_type: String, transaction_num: Str ...