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:
And I can’t understand the reason why and [more importantly] how to fix it.
2
Answers
Try this:
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 🙂
Hope this should work as All the setup I have worked inclined with your requirement,
Here are version’s those I am using,
Here is firebase init’n,
Here is the firebase-messaging-sw.js at
public
folderHope this get your working!.