Firebase Push Notification Implementation
Overview
This document describes the integration and implementation of Firebase Cloud Messaging (FCM) push notifications within the backend service, built using NestJS. The system enables real-time and asynchronous notifications to users’ devices (web, Android, iOS) for various events, such as appointment updates, test assignments, and order status changes.
1. Firebase Setup
- Firebase Project: A Firebase project is created in the Firebase Console.
- Service Account: The backend uses a service account JSON file (
firebase-service-account.json
) for server authentication. - FCM Configuration: The Firebase Admin SDK is initialized in the backend using the service account credentials.
// backend/src/config/firebase.config.ts import * as admin from 'firebase-admin'; import * as serviceAccount from '../../firebase-service-account.json'; admin.initializeApp({ credential: admin.credential.cert(serviceAccount as admin.ServiceAccount), }); export const messaging = admin.messaging();
2. User FCM Token Management
- Saving FCM Token: When a user logs in or registers a device, the frontend sends the FCM token to the backend, which stores it in the user’s record.
- Deleting FCM Token: On logout or device removal, the token is deleted from the user’s record.
// backend/src/notification/notification.service.ts async saveFcmToken(userId: string, token: string) { ... } async deleteFcmToken(userId: string) { ... }
3. Sending Push Notifications
- Notification Service: The
NotificationService
contains the logic for sending FCM notifications. - sendFcmNotification Method: This method retrieves the user’s FCM token and sends a notification using the Firebase Admin SDK.
async sendFcmNotification(userId: string, title: string, body: string, data?: any) { const user = await this.usersRepository.findOne({ where: { id: userId } }); if (!user || !user.fcmToken) return null; const message = { token: user.fcmToken, notification: { title, body }, data: { ...data, click_action: 'FLUTTER_NOTIFICATION_CLICK', sound: 'default' }, android: { ... }, apns: { ... }, webpush: { ... }, }; return await messaging.send(message); }
- Trigger Points: Notifications are sent for various events, such as:
- Appointment creation, rescheduling, or cancellation
- Test assignments to technicians or marketers
- Test result availability
- Order status updates
4. Notification Creation and Storage
- Database Storage: Every notification is stored in the
Notification
entity, which includes fields such astitle
,message
,type
,referenceId
, anduser
. - WebSocket Real-Time Notification: In addition to FCM, notifications are also sent via WebSocket for real-time updates in the frontend.
async createNotification(data: { ... }) { const notification = this.notificationRepository.create({ ... }); const savedNotification = await this.notificationRepository.save(notification); // WebSocket this.notificationGateway.sendNotification(data.userId, savedNotification); // FCM await this.sendFcmNotification(data.userId, data.title, data.message, { ... }); }
5. Notification Data Structure
- Frontend Format: Notifications are mapped to a frontend-friendly structure, including:
create_time
description
reference_id
is_viewed
name
notification_type
update_time
user_id
uuid
6. Extensibility
- Bulk Notifications: The system supports sending notifications to multiple users at once.
- Role-Based Notifications: Different notification types and messages are sent based on user roles (e.g., technician, marketer, coordinator).
7. Error Handling and Logging
- All FCM errors are logged but do not interrupt the main application flow.
- Internal server errors are handled gracefully and reported for debugging.
8. Security Considerations
- FCM tokens are stored securely and only accessible to authenticated backend services.
- Only authorized users can trigger notification events.
Conclusion
This implementation provides a robust, scalable, and extensible push notification system using Firebase Cloud Messaging, integrated seamlessly with the backend’s business logic and user management. It ensures users are kept up-to-date in real time, improving engagement and operational efficiency.
Top comments (0)