简体   繁体   中英

Next Js cant find Service messaging (firebase-cloud-messaging)

Hi I using firebase cloud messaging in next.js project and when I try to run or build my project I get this error:

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' }

my code: it seems this problem happens because using 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);
            // Track the token -> client mapping, by sending to backend server
            // show on the UI that permission is secured
        } else {
            console.log('No registration token available. Request permission to generate one.');
            setTokenFound(false);
            // shows on the UI that permission is required
        }
    }).catch((err) => {
        console.log('An error occurred while retrieving token. ', err);
        // catch error while creating client token
    });
}

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));

    }, []);

i had same issue turns out it was firebase v9 issue

using firebase v8 worked for me

npm i firebase@8.2.3

after installing v8 don't forget to change syntax its firebase.initializeApp(firebaseConfig);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM