I decided to incorporate push notifications into my Next.js (version 12) app, so I integrated Firebase Cloud Messaging. Here is the implementation:
import { initializeApp, getApp, getApps } from "firebase/app"
import { getMessaging, getToken } from "firebase/messaging"
import { firebaseConfig } from "./config"
const app = !getApps.length ? initializeApp(firebaseConfig) : getApp()
I also added the cloudMessaging function to retrieve the FCM token and the onMessageListener function to display foreground messages.
export const cloudMessaging = async () => {
const token = await isTokenAvailable()
if (token !== null) {
return Promise.resolve({
status: true,
token: token,
})
}
try {
const permission = await Notification.requestPermission()
const messaging = getMessaging(app)
console.log(messaging)
console.log(permission)
if (permission === "granted") {
const FCM_TOKEN = await getToken(messaging, {
vapidKey: process.env.NEXT_PUBLIC_FCM_VAPID_KEY,
})
if (FCM_TOKEN) {
localStorage.setItem("fcm_token_prac", FCM_TOKEN)
return Promise.resolve({
status: true,
token: FCM_TOKEN,
})
}
}
} catch (err) {
console.log(err, "cloudmessaging error")
return Promise.resolve({
status: false,
})
}
}
export const onMessageListener = () => {
const messaging = getMessaging(app)
console.log(messaging)
return new Promise((res) => {
messaging.onMessage((payload) => {
res(payload)
})
})
}
These functions are invoked from my Layout component.
useEffect(() => {
firebaseInit()
async function firebaseInit() {
try {
await cloudMessaging()
} catch (err) {
console.log(err)
}
}
}, [])
useEffect(() => {
onMessageListener()
.then((payload) => {
console.log(payload, "onMessageListener")
})
.catch((err) => console.log(err, "onMessageListener useEffect"))
}, [])
However, I encountered this error in my console:
TypeError: messaging.onMessage is not a function
at eval (firbase.js?100f:58:15)
at new Promise (<anonymous>)
at onMessageListener (firbase.js?100f:57:10)
at eval (Layout.js?4f8d:33:22)
at commitHookEffectListMount (react-dom.development.js?ac89:23049:1)
I am struggling to identify where I went wrong. Can someone assist me in rectifying this?