From 62545d0114ff3028c397c7ff1f54d3861e1e5cec Mon Sep 17 00:00:00 2001 From: pradeepkumar Date: Mon, 6 Apr 2026 14:06:55 +0530 Subject: [PATCH] fix --- .../providers/notification-provider.tsx | 2 +- src/services/notification.service.ts | 74 +++++++++++++++---- 2 files changed, 62 insertions(+), 14 deletions(-) diff --git a/src/components/providers/notification-provider.tsx b/src/components/providers/notification-provider.tsx index e194d60..f597d33 100644 --- a/src/components/providers/notification-provider.tsx +++ b/src/components/providers/notification-provider.tsx @@ -47,7 +47,7 @@ export function NotificationProvider() { const registered = await notificationService.requestPermissionAndRegister(); console.log('[NotificationProvider] Registration result:', registered); if (registered) { - unsubscribe = notificationService.setupForegroundHandler((payload) => { + unsubscribe = await notificationService.setupForegroundHandler((payload) => { console.log('[NotificationProvider] Foreground message received:', payload); addToast(payload); }); diff --git a/src/services/notification.service.ts b/src/services/notification.service.ts index 13da655..429146b 100644 --- a/src/services/notification.service.ts +++ b/src/services/notification.service.ts @@ -1,27 +1,65 @@ -import { app, getMessaging, getToken, onMessage, isSupported } from '@/lib/firebase'; import api from './api'; const VAPID_KEY = process.env.NEXT_PUBLIC_FIREBASE_VAPID_KEY; class NotificationService { private currentToken: string | null = null; + private messaging: any = null; + + private async getFirebaseMessaging() { + if (this.messaging) return this.messaging; + + try { + const { getMessaging, isSupported } = await import('firebase/messaging'); + const supported = await isSupported(); + if (!supported) { + console.log('[Notifications] Firebase messaging not supported'); + return null; + } + + const { initializeApp, getApps } = await import('firebase/app'); + const firebaseConfig = { + apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY, + authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN, + projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID, + storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET, + messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID, + appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID, + }; + const app = getApps().length === 0 ? initializeApp(firebaseConfig) : getApps()[0]; + this.messaging = getMessaging(app); + return this.messaging; + } catch (error) { + console.error('[Notifications] Failed to init Firebase messaging:', error); + return null; + } + } async requestPermissionAndRegister(): Promise { try { - // Check if messaging is supported in this browser - const supported = await isSupported(); - if (!supported) { - console.log('[Notifications] Firebase messaging not supported in this browser'); - return false; - } + if (typeof window === 'undefined') return false; if (!VAPID_KEY) { console.warn('[Notifications] VAPID key not configured'); return false; } + if (!('Notification' in window)) { + console.log('[Notifications] Notifications API not available'); + return false; + } + + if (!('serviceWorker' in navigator)) { + console.log('[Notifications] Service workers not supported'); + return false; + } + + const messaging = await this.getFirebaseMessaging(); + if (!messaging) return false; + // Request notification permission const permission = await Notification.requestPermission(); + console.log('[Notifications] Permission:', permission); if (permission !== 'granted') { console.log('[Notifications] Permission denied'); return false; @@ -31,9 +69,13 @@ class NotificationService { const registration = await navigator.serviceWorker.register( '/firebase-messaging-sw.js' ); + console.log('[Notifications] Service worker registered:', registration.scope); + + // Wait for service worker to be ready + await navigator.serviceWorker.ready; // Get FCM token - const messaging = getMessaging(app); + const { getToken } = await import('firebase/messaging'); const token = await getToken(messaging, { vapidKey: VAPID_KEY, serviceWorkerRegistration: registration, @@ -44,6 +86,7 @@ class NotificationService { return false; } + console.log('[Notifications] FCM token obtained:', token.substring(0, 20) + '...'); this.currentToken = token; // Register token with backend @@ -52,7 +95,7 @@ class NotificationService { device: 'web', }); - console.log('[Notifications] FCM token registered'); + console.log('[Notifications] FCM token registered with backend'); return true; } catch (error) { console.error('[Notifications] Registration failed:', error); @@ -73,12 +116,16 @@ class NotificationService { } } - setupForegroundHandler( + async setupForegroundHandler( callback: (payload: { title: string; body: string; data?: Record }) => void - ): (() => void) | null { + ): Promise<(() => void) | null> { try { - const messaging = getMessaging(app); + const messaging = await this.getFirebaseMessaging(); + if (!messaging) return null; + + const { onMessage } = await import('firebase/messaging'); const unsubscribe = onMessage(messaging, (payload) => { + console.log('[Notifications] Foreground message:', payload); callback({ title: payload.notification?.title || 'New Notification', body: payload.notification?.body || '', @@ -86,7 +133,8 @@ class NotificationService { }); }); return unsubscribe; - } catch { + } catch (error) { + console.error('[Notifications] Foreground handler failed:', error); return null; } }