Files
SweetHome/app/utils/firebase.js

86 lines
2.3 KiB
JavaScript
Raw Normal View History

import { initializeApp, getApps } from "firebase/app";
import { getMessaging, getToken, onMessage } from "firebase/messaging";
const firebaseConfig = {
apiKey: "AIzaSyBZV7KBLRJSTApahfrO8lBesmIM3zNRSaY",
authDomain: "sweet-home-b2766.firebaseapp.com",
projectId: "sweet-home-b2766",
storageBucket: "sweet-home-b2766.firebasestorage.app",
messagingSenderId: "602865114600",
appId: "1:602865114600:web:ed9b6754940507a6ab585d",
measurementId: "G-M2V95NBJLX",
};
// Initialize Firebase (avoid duplicate init in SSR)
2026-06-24 06:53:18 -07:00
const app =
getApps().length === 0 ? initializeApp(firebaseConfig) : getApps()[0];
// Get messaging instance (only works in browser)
let messaging = null;
if (typeof window !== "undefined" && "serviceWorker" in navigator) {
try {
messaging = getMessaging(app);
2026-06-24 06:53:18 -07:00
} catch (e) {}
}
// Request notification permission and get FCM token
export async function requestNotificationPermission() {
if (typeof window === "undefined") return null;
try {
const permission = await Notification.requestPermission();
if (permission !== "granted") {
return null;
}
2026-06-24 06:53:18 -07:00
const registration = await navigator.serviceWorker.register(
"/firebase-messaging-sw.js"
);
const token = await getToken(messaging, {
2026-06-24 06:53:18 -07:00
vapidKey:
"BGZ4Fo8rRhoTdStLGlCySDZOnAX4ekCA0e3HDWXL5uEi2kOnXynYjbaDbY15002phUrFqxBpPPFHgfH2VhrmFDU",
serviceWorkerRegistration: registration,
});
// Send token to backend
if (token) {
try {
const authToken = localStorage.getItem("auth_token");
2026-06-24 06:53:18 -07:00
if (authToken) {
2026-06-24 06:53:18 -07:00
const apiBase =
process.env.NEXT_PUBLIC_API_URL ||
"https://45.93.137.91.nip.io/api";
await fetch(`${apiBase}/User/SetFCMToken`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${authToken}`,
},
2026-06-24 06:53:18 -07:00
body: JSON.stringify({
token,
deviceType: 2,
}),
});
}
2026-06-24 06:53:18 -07:00
} catch (err) {}
}
return token;
} catch (err) {
return null;
}
}
// Listen for foreground messages
export function onForegroundMessage(callback) {
if (!messaging) return () => {};
return onMessage(messaging, (payload) => {
callback(payload);
});
}
2026-06-24 06:53:18 -07:00
export { app, messaging };