skip to Main Content

In my Nextjs project I’m trying to implement push notification with firebase messaging (my firebase version is 8.10.0), after creating the firebase-messaging-sw.js file in my public folder:

importScripts(
  "https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"
);
importScripts(
  "https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging.js"
);

const firebaseConfig = {
  apiKey: "***",
  authDomain: "***",
  projectId: "***",
  storageBucket: "***",
  messagingSenderId: "***",
  appId: "***",
  measurementId: "***"
};

firebase.initializeApp(firebaseConfig)
const messaging = firebase.messaging();

messaging.onBackgroundMessage((payload) => {
  const notificationTitle = payload.notification.title;
  const notificationOptions = {
    body: payload.notification.body,
    icon: null,
  };

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

I now created a [utility] file (that I named Firebase.js) where I’ll implement helper functions like the request token function.

Here is a code snippet from that file:

import firebase from "firebase/app";
import "firebase/messaging";

const firebaseConfig = {
    apiKey: "***",
    authDomain: "***",
    projectId: "***",
    storageBucket: "***",
    messagingSenderId: "***",
    appId: "***",
    measurementId: "***"
};

!firebase.apps.length && firebase.initializeApp(firebaseConfig);

const messaging = firebase.messaging();

export const requestForToken = () => {
   // func that generates and returns a FCM token
};

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

Now to use those functions I created another file Notification.js:

import React, { useState, useEffect } from "react";
import { toast } from "react-toastify";
import { requestForToken, onMessageListener } from "./Firebase";

const Notification = () => {
    const [notification, setNotification] = useState({ title: "", body: "" });

    useEffect(() => {
        requestForToken();
    }, []);
  
    const ToastDisplay = () => {
        return (
            <>
                <b>{notification?.title} </b>
                <p>{notification?.body}</p>
            </>
        );
    };

    const notify = () => toast(<ToastDisplay />);
    
    useEffect(() => {
        notification?.title && notify();
    }, [notification]);

    onMessageListener()
        .then((payload) => {
            setNotification({
                title: payload?.notification?.title,
                body: payload?.notification?.body,
            });
        })
        .catch((err) => console.log("failed: ", err));

    return <></>;
};

export default Notification;

I imported Notification.js in _app.js and when I run my app I get the following error:
enter image description here

And I can’t understand the reason why and [more importantly] how to fix it.

2

Answers


  1. Try this:

    import { initializeApp } from "firebase/app";
    import { getMessaging, onMessage } from "firebase/messaging";
    
    const firebaseConfig = {
        // ...
    };
    
    const app = initializeApp(firebaseConfig);
    const messaging = getMessaging(app);
    
    onMessage(messaging, (payload) => {
        console.log('Message received. ', payload);
        // ...
    })
    
    // ...
    

    Also take a look into firebase docs

    EDIT:
    Take a look here too. It’s showing how to receive messages into client.

    Hope I’ve helped you with something 🙂

    Login or Signup to reply.
  2. Hope this should work as All the setup I have worked inclined with your requirement,

    Here are version’s those I am using,

    "next": "^12.0.7",
    "firebase": "^8.6.8",
    "@firebase/installations": "^0.5.4"
    
    

    Here is firebase init’n,

    /* eslint-disable import/prefer-default-export */
    // import firebase from 'firebase/app';
    import firebaseClient from "firebase/app";
    import "firebase/installations";
    import "firebase/auth";
    import "firebase/messaging";
    import "firebase/functions";
    import "firebase/analytics";
    
    const CLIENT_CONFIG = {
      apiKey: "***",
      authDomain: "***",
      databaseURL: "***",
      projectId: "***",
      storageBucket: "***",
      messagingSenderId: "***",
      appId: "***",
      measurementId: "***",
    };
    if (typeof window !== "undefined" && firebaseClient.apps?.length <= 0) {
      firebaseClient.initializeApp(CLIENT_CONFIG);
    
      (window as any).firebase = firebaseClient;
      if (firebaseClient.messaging.isSupported()) {
        const msg = firebaseClient.messaging();
        const creds = {
          vapidKey: process.env.NEXT_PUBLIC_FIREBASE_WEB_FCM_TOKEN
            ? process.env.NEXT_PUBLIC_FIREBASE_WEB_FCM_TOKEN
            : "",
        };
        msg.getToken(
          creds,
        )
          .then((token) => {
            // Send the token to your app server if notification service granted
            console.log(token);
          })
          .catch((err) => {
            // If user blocks notification service
            console.log(err);
          });
      }
    }
    
    export { firebaseClient };
    

    Here is the firebase-messaging-sw.js at public folder

    /* eslint-disable space-before-function-paren */
    if ("serviceWorker" in navigator) {
      navigator.serviceWorker
        .register("../firebase-messaging-sw.js")
        .then((registration) => {
          console.log("Registration successful, scope is:", registration.scope);
        })
        .catch((err) => {
          console.log("Service worker registration failed, error:", err);
        });
    }
    

    Hope this get your working!.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search