Next Js is having trouble locating the Service messaging component (firebase-cloud-messaging)

Hey there! I'm currently working on a project with Next JS that involves using Firebase Cloud Messaging. However, I've encountered an error when trying to run or build the project:

info - Checking validity of types
info - Creating an optimized production build
info - Compiled successfully info - Collecting page data ...node:internal/process/promises:246 triggerUncaughtException(err, true /* fromPromise */); ^

Error: Service messaging is not available at Provider.getImmediate (file:///I:/Work/Web/Php/Project/wamp/www/test/node_modules/@firebase/component/dist/esm/index.esm2017.js:147:23) at getMessagingInWindow (I:\Work\Web\Php\Project\wamp\www\test\node_modules@firebase\messaging\dist\index.cjs.js:1460:74) at I:\Work\Web\Php\Project\wamp\www\test.next\server\pages_app.js:117:83 { type: 'Error' }

Here's my code snippet: It appears this issue arises due to the use of getMessaging.

firbase.js

import { initializeApp } from 'firebase/app';
import { getMessaging, getToken, onMessage } from "firebase/messaging";

var firebaseConfig = {
    apiKey: "----",
    authDomain: "---",
    projectId: "---",
    storageBucket: "---",
    messagingSenderId: "---",
    appId: "---",
    measurementId: "---"
};

const firebaseApp = initializeApp(firebaseConfig);
const messaging =  getMessaging(firebaseApp);

export const fetchToken = (setTokenFound) => {
    return getToken(messaging, {vapidKey: '---'}).then((currentToken) => {
        if (currentToken) {
            console.log('current token for client: ', currentToken);
            setTokenFound(true);
        } else {
            console.log('No registration token available. Request permission to generate one.');
            setTokenFound(false);
        }
    }).catch((err) => {
        console.log('An error occurred while retrieving token. ', err);
    });
}

export const onMessageListener = () =>
    new Promise((resolve) => {
        onMessage(messaging, (payload) => {
            resolve(payload);
        });
    });

firebase-messaging-sw.js

// Scripts for firebase and firebase messaging
importScripts('https://www.gstatic.com/firebasejs/9.6.11/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/9.6.11/firebase-messaging-compat.js');

// Initialize the Firebase app in the service worker by passing the generated config
const firebaseConfig = {
     apiKey: "----",
    authDomain: "---",
    projectId: "---",
    storageBucket: "---",
    messagingSenderId: "---",
    appId: "---",
    measurementId: "---"
};

firebase.initializeApp(firebaseConfig);

// Retrieve firebase messaging
const messaging = firebase.messaging();

messaging.onBackgroundMessage(function(payload) {
    console.log('Received background message ', payload);

    const notificationTitle = payload.notification.title;
    const notificationOptions = {
        body: payload.notification.body,
    };

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

_app.tsx

import {fetchToken,onMessageListener} from '../tools/firebase'
    const [notification, setNotification] = useState({title: '', body: ''});
  const [isTokenFound, setTokenFound] = useState(false);
useEffect(() => {
        fetchToken(setTokenFound)
        onMessageListener().then(payload => {
            setNotification({title: payload.notification.title, body: payload.notification.body})

            console.log(payload);
        }).catch(err => console.log('failed: ', err));

    }, []);

Answer №1

I encountered a similar issue, only to discover that it was related to Firebase v9.

Switching back to using Firebase v8 resolved the problem for me.

npm i <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="14727d667176756771542c3a263a27">[email protected]</a>

Remember, after installing v8, be sure to update the syntax to

firebase.initializeApp(firebaseConfig);

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

Angular JS: Saving information with a promise

One dilemma I am facing is figuring out where to store data that needs to be accessed in the final callbacks for an http request. In jQuery, I could easily handle this by doing the following: var token = $.get('/some-url', {}, someCallback); tok ...

Animating the dimensions of objects in THREEjs

In my project using THREE.js, I am aiming to create a captivating animation where an object gradually shrinks into nothingness. After exploring solutions on Three.js - Animate object size, I found methods to adjust the size of an object. However, the chan ...

Python Firebase POST request encounters an unexpected token in the position 0, signaling the end of the file

I am attempting to use Firebase to send a message to a specific client. The code I am currently using for testing is as follows: import json import requests import urllib def send_message(): server = "https://fcm.googleapis.com/fcm/send" api_key ...

What is the best way to style a value within a v-for loop inside an el-option element in Element UI?

I'm looking for a way to format the value in label(item.value) as a decimal within a v-for loop. Below is my code snippet: <el-form-item :label="label" :required="required" prop="Jan"> <el-select v-model=& ...

Sending HTML parameters to a PHP file

I have been trying to pass the parameters from the current HTML page to a PHP page using a form. In my header in the HTML, I currently have the following function: <script> function getURLParameter(name) { return decodeURIComponent((new Re ...

How should I manage objects that are passed by reference in the context of functional programming?

Lately, I have been experimenting with some code in an attempt to delve deeper into functional programming. However, I seem to have hit a snag. I am struggling with handling an object. My goal is to add key-value pairs to an object without reassigning it, ...

How to Extract YouTube Audio URL on an iPhone

I have been working on a JavaScript code that can fetch the direct download URL for videos from the mobile YouTube website. [webView stringByEvaluatingJavaScriptFromString:@"function getURL() {var player = document.getElementById('player'); var ...

What is the best way for library creators to indicate to VSCode which suggested "import" is the correct one?

As a library creator, I have noticed that VSCode often suggests incorrect imports to users. For instance, VSCode typically suggests the following import: import useTranslation from 'next-translate/lib/esm/useTranslation' However, the correct im ...

Node.js: Promise chain abruptly stops after reaching a predefined limit without causing any errors

Currently, I am attempting to perform a straightforward operation in nodejs using promises. My task involves working with an array that consists of objects. These objects contain query parameters for a URL that I need to access through a GET request. As th ...

How to populate a database with Facebook data by utilizing AJAX post and PHP

I've been developing a Facebook Canvas game and had it running smoothly on my localhost along with a local database via phpMyAdmin. However, after moving it online, I've encountered an issue with the database. Previously, the game would grab pla ...

Encountering difficulties while trying to install ng2-material in Angular 2

I'm attempting to utilize a data table with the ng2-material library from ng2-material as shown below: <md-data-table [selectable]="true"> <thead> <tr md-data-table-header-selectable-row> <th class="md-text-cell">M ...

Dynamic fields added using JavaScript are not recognized by PHP

I have a MySQL database where orders are stored along with various activities. My PHP/HTML page retrieves these activities when an order is clicked and allows users to modify them using a form. Upon submission, another PHP file updates the database by loop ...

Node.js encountering unexpected pattern during RegExp match

Currently, I'm developing a script that aims to simplify local testing by creating a Node server for all my Lambda functions. My main challenge lies in extracting all the dbconfig objects from each file. To test out various patterns, I rely on . Surpr ...

Run an npm script located in a different package

Imagine I have two node packages, one named parent and the other named child. The child package contains a package.json file with some scripts. Is it viable to merge the scripts from child into the context of parent? For instance: child/package.json: "s ...

Unable to transfer data through Ionic popover

I've encountered an issue when trying to pass data to my popover component, as the data doesn't seem to be sent successfully. Code HTML <div class="message" id="conversation" *ngFor="let message of messages.notes"> <ion-row class= ...

How can you determine the number of elements that match in two arrays?

As a coding newbie, I'm looking to create a JavaScript function that compares two arrays and assigns a score based on the number of matching elements. However, when I attempt to run it in Chrome's console, I receive an error message stating that ...

Executing a function when clearing an autocomplete textfield in Material-UI

Currently, I am working with a material-ui autocomplete text field in order to filter a list. My goal is to have the list repopulate back to its original form when the user deletes the text and presses the enter key. After my research, it seems like the ...

Embracing the node mindset with a Java foundation

As a Java Developer, I have become accustomed to working in a sequential manner where tasks are executed one after the other or concurrently with multiple threads. The organization of code in a sequential way seemed logical under this paradigm. However, wh ...

Unable to deliver FCM push notifications through the application server

Initially, my proficiency in English is limited. I kindly ask for your understanding... I have a desire to implement FCM for sending PUSH notifications to users. As a result, I developed an Android application capable of receiving Push notifications from ...

When using QML, functions like Object.keys, Object.values, and JSON.stringify may return unexpected empty results

I have written a code that exposes a C++ object to QML, and I want to verify the declared properties of the object using native JS methods. However, they are not working as expected. I created a method called FizzBuzzDerived.properties, which functions cor ...