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

Launching the Node.js application on Heroku resulted in encountering an issue: "Application error - There was a problem within the application

When I access the browser using http://localhost:8080/, I can see the message Hello World with Express. I am currently trying to deploy this application on Heroku. I have followed the tutorial provided by Heroku. 1) Create a new app 2) Choose an App name ...

Sails.js seems to be malfunctioning, as it does not seem to be recognizing the term 'sails'

It seems like I'm encountering an issue with the 'sails' command not being recognized on my Windows 10 system. Despite following all the installation steps, including globally installing Sails.js through npm and ensuring Node is installed, I ...

Guide on setting up ShareThis on a Vue.js project

I attempted to include this code in the public index.html file: <script type='text/javascript' src='https://platform-api.sharethis.com/js/sharethis.js#property=5f4e15b2e56e550012ae1e77&product=inline-share-buttons' async='a ...

Is it possible to establish role-based access permissions once logged in using Angular 6?

Upon logging in, the system should verify the admin type and redirect them to a specific component. For example, an HOD should access the admi dashboard, CICT should access admin2 dashboard, etc. Below is my mongoose schema: const mongoose = require(&apo ...

Achieving 10 touchdowns within a set of 5 plays during a football game

Receiving a page from an external site where I have no control. The table structure is as follows: <table><tbody> <!-- headers --> <tr><td></td> <td></td> <td></td> <td>< ...

React Express Error: Unable to access property 'then' of undefined

I'm facing an issue while trying to server-side render my react app for users who have disabled JavaScript and also for better search engine optimization. However, I am encountering the following error: TypeError: Cannot read property 'then' ...

Javascript: Anticipating a Return from an Argument

I am currently working on a function that requires an attribute to respond before proceeding with its process. The function call is structured like this : processResult(getResult()); The issue lies in the fact that the getResult function takes some time ...

Ways to avoid data looping in jQuery Ajax requests

This is in relation to the assignment of multiple users using the Select2 plugin, Ajax, and API. The situation involves a function that contains 2 Ajax calls with different URLs. Currently, there are pre-selected users stored in the database. The selection ...

You cannot use a relative path when inserting an image tag in React

I am having an issue with my img tag not loading the desired image when using a relative src path in my React project. When I try: //import { ReactComponent } from '*.svg'; import React from 'react'; import firebase from "./firebas ...

Customizing order and limit features in AngularJS

I have a collection of items that I need to organize into separate lists based on priority levels. items = [ {'type': 2, 'priority': 1, 'name': 'one'}, {'type': 1, 'priority': 2, 'na ...

Steps for creating a basic prioritized event listener system in JavaScript

I am currently working on an event/listener manager that has the following function: var addListener = function(event, listener) { myListeners[event].push(listener); //assume this code works } However, I now need to modify it so that it appears a ...

The input value is displaying one value, but the output is showing a different value

I am encountering a unique issue and could really use some assistance. <input class="testVal" type="number" id="GT_FIRING_TEMPERATURE" value="-17" name="degC" onchange="angular.element(this).scope().unitConversion(value,name, id)"> Despite the valu ...

How to create a basic calculator in AngularJS with two textboxes specifically designed for calculating squares?

My code snippet is as follows: <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> </head> <body> <div ng-app="app"> <div ng-controller="Calcu ...

executing code on each of the sub-routes within Nextjs

Within my file structure, I have various folders such as auth and panel. In the panel folder, there are additional subfolders like exam, article, and project. I am looking to execute a code or function across all routes within the panel folder. For insta ...

Facing issues with dynamic imports in Jest and React Testing Library while testing Next.js 12? Try using SWC instead of babel for a smoother experience

I am encountering issues with testing dynamic imported components in Next.js 12. Here is some technical information: Next.js 12 uses SWC instead of Babel React 18 Jest + React Testing Library Below is an example: import styles from '@/pages/index.mo ...

How to efficiently send multiple objects in response to a single GET request with Express and Node.js

The code snippet I am working with looks like this - sendServer.get('/download',function(request,response){ var status="SELECT * from poetserver.download where status='0'"; console.log(status) connection.query(status,function(error,ro ...

Exploring the process of retrieving data from localStorage in Next.js 13

Having recently delved into the realm of Next JS, I've encountered a hurdle when it comes to creating middleware within Next. My aim is to retrieve data from local storage, but I keep hitting roadblocks. middleware.ts import { key, timeEncryptKey, to ...

Using the split and join methods in PHP for Javascript operations

Can you assist me with writing this code in PHP? I've attempted multiple times but I can't seem to get it right. Any help would be greatly appreciated! return s.split(/\r?\n/).join("<br>"); Thank you in advance! ...

Developing UIs in React that change dynamically according to the radio button chosen

Problem Statement I am currently developing a web application feature that computes the heat insulation factor for a specific area. You can view the live demonstration on Codesandbox

Tips for resizing user-uploaded images to fit the required dimensions outlined in the design draft using CSS or JavaScript

Hey everyone! I'm facing an issue but my English isn't great. I'll do my best to explain it thoroughly, and if anything is unclear, please feel free to let me know! So here's the problem: today there's a block for users to upload p ...