|
| 1 | +import { initializeApp, getApps, getApp, FirebaseApp } from 'firebase/app' |
| 2 | +import { getMessaging, getToken, Messaging } from 'firebase/messaging' |
| 3 | + |
| 4 | +const firebaseConfig = { |
| 5 | + apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY, |
| 6 | + authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN, |
| 7 | + projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID, |
| 8 | + storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET, |
| 9 | + messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID, |
| 10 | + appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID, |
| 11 | + measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID, |
| 12 | +} |
| 13 | + |
| 14 | +const firebaseApp: FirebaseApp = !getApps().length |
| 15 | + ? initializeApp(firebaseConfig) |
| 16 | + : getApp() |
| 17 | + |
| 18 | +let messaging: Messaging | null = null |
| 19 | + |
| 20 | +const initializeMessaging = () => { |
| 21 | + if (typeof window !== 'undefined') { |
| 22 | + if (!messaging) { |
| 23 | + messaging = getMessaging(firebaseApp) |
| 24 | + } |
| 25 | + } |
| 26 | + return messaging |
| 27 | +} |
| 28 | + |
| 29 | +const requestFcmToken = async (): Promise<string | null> => { |
| 30 | + const messagingInstance = initializeMessaging() |
| 31 | + |
| 32 | + if (!messagingInstance) return null |
| 33 | + |
| 34 | + try { |
| 35 | + const serviceWorkerRegistration = |
| 36 | + await navigator.serviceWorker.register('/sw.js') |
| 37 | + |
| 38 | + const permission = await Notification.requestPermission() |
| 39 | + if (permission !== 'granted') { |
| 40 | + return null |
| 41 | + } |
| 42 | + |
| 43 | + const currentToken = await getToken(messagingInstance, { |
| 44 | + vapidKey: process.env.NEXT_PUBLIC_FIREBASE_VAPID_KEY, |
| 45 | + serviceWorkerRegistration: serviceWorkerRegistration, |
| 46 | + }) |
| 47 | + |
| 48 | + return currentToken |
| 49 | + } catch (err) { |
| 50 | + console.error('An error occurred while retrieving token. ', err) |
| 51 | + return null |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +export { firebaseApp, messaging, requestFcmToken } |
0 commit comments