I am using App Router.
app/layout.tsx
return (
<PushNotificationLayout />
)
app/PushNotificationLayout.tsx
"use client";
import React, { useEffect } from "react";
import * as firebase from "firebase/app";
import "firebase/messaging";
import { firebaseCloudMessaging } from "../../utils/firebase";
import dynamic from "next/dynamic";
function PushNotificationLayout({ children }) {
const [message, setMessage] = React.useState();
useEffect(() => {
setToken();
if ("serviceWorker" in navigator) {
navigator.serviceWorker.addEventListener("message", (event) => {
// Do something
});
}
async function setToken() {
try {
const token = await firebaseCloudMessaging.init();
...
} catch (error) {}
}
}, []);
function getMessage() {
firebase.messaging().onMessage(
(message) => {
...
},
(e) => {...}
);
}
return (...);
}
// I tried to disable ssr but not working
export default dynamic(() => Promise.resolve(PushNotificationLayout), {
ssr: false,
});
/utils/firebase.js
import "firebase/messaging";
import firebase from "firebase/app";
import localforage from "localforage";
const firebaseCloudMessaging = {
init: async () => {
localforage.removeItem("fcm_token");
if (!firebase?.apps?.length) {
firebase?.initializeApp({...});
try {
const messaging = firebase.messaging();
const tokenInLocalForage = await localforage.getItem("fcm_token");
if (tokenInLocalForage !== null) {
return tokenInLocalForage;
}
const status = await Notification.requestPermission();
if (status && status === "granted") {
const fcm_token = await messaging.getToken(...);
if (fcm_token) {
localforage.setItem("fcm_token", fcm_token);
return fcm_token;
}
}
} catch (error) {...}
}
},
};
export { firebaseCloudMessaging };
I thought it might be related to localforage
, which uses indexDB internally because of the error message ReferenceError: IDBIndex is not defined
.
Therefore I tried to disable ssr by
export default dynamic(() => Promise.resolve(PushNotificationLayout), {
ssr: false,
});
But it still renders in the server, because I saw the same error in the server side instead of client side.
I also tried to comment out <PushNotificationLayout />
in layout.tsx, and the error is gone