9. Cloud Messaging: Push Notifications & Engagement
Push Notifications with Firebase Cloud Messaging
Firebase Cloud Messaging (FCM) is a cross-platform messaging solution for sending notifications and data messages to iOS, Android, and web applications. FCM handles the delivery of messages to over a billion devices, providing reliable push notifications with minimal latency.
FCM is the foundation of Firebase's engagement features. It supports notification messages (displayed in the system tray) and data messages (handled by your app). Notifications can be targeted to specific devices, topics, or user segments. FCM integrates with Analytics for engagement tracking. Understanding FCM is essential for building applications that re-engage users. Use notifications for time-sensitive updates, marketing messages, and user engagement. Implement proper permission handling for web notifications. Use topics for broadcasting to user segments.
Sending Notifications
Notifications are sent via the FCM API using the Firebase Admin SDK, the REST API, or the Firebase Console. You can send to specific device tokens, topics, or conditions. Notification messages are displayed automatically by the system. Data messages are handled by your app's service worker. The Admin SDK provides a simple API for sending messages. For web applications, use the service worker to handle data messages. Always handle permission denial gracefully. Use notification channels for Android to group notifications. The FCM API supports rich notifications with images, buttons, and deep links.
// Sending a notification using Firebase Admin SDK import * as admin from 'firebase-admin'; admin.initializeApp(); // Send to a specific device token const message = { notification: { title: 'New Message', body: 'You have a new message from Alice', }, data: { click_action: 'FLUTTER_NOTIFICATION_CLICK', conversation_id: '12345', }, token: 'device-token-here', }; // Send to a topic const topicMessage = { notification: { title: 'Breaking News', body: 'Major update on your favorite topic', }, topic: 'news', }; // Send await admin.messaging().send(message); await admin.messaging().send(topicMessage);
Web Push Notifications
Web push notifications are handled by service workers. The service worker receives push events and displays the notification. For web apps, you need to request permission and register the service worker. The Firebase SDK handles the service worker registration. You can customize the notification appearance using the payload. Web push works on Chrome, Firefox, Edge, and Safari. Always test notifications on different browsers. Use the Notification API for custom notification handling. For iOS Safari, notifications require the web app to be installed to the home screen. Web push is a powerful way to re-engage users on the web.
// Register service worker for web push import { initializeApp } from 'firebase/app'; import { getMessaging, getToken, onMessage } from 'firebase/messaging'; const app = initializeApp(firebaseConfig); const messaging = getMessaging(app); // Request permission and get token const permission = await Notification.requestPermission(); if (permission === 'granted') { const token = await getToken(messaging, { vapidKey: 'your-vapid-key-here' }); console.log('Token:', token); } // Handle foreground messages onMessage(messaging, (payload) => { console.log('Message received:', payload); // Show in-app notification }); // Service worker (public/firebase-messaging-sw.js) importScripts('https://www.gstatic.com/firebasejs/9.x/firebase-app-compat.js'); importScripts('https://www.gstatic.com/firebasejs/9.x/firebase-messaging-compat.js'); firebase.initializeApp(firebaseConfig); const messaging = firebase.messaging(); messaging.onBackgroundMessage((payload) => { console.log('Background message:', payload); // Customize notification });
Topic Messaging and Segmentation
Topics allow you to send messages to groups of users who opt in to specific topics. Users can subscribe to multiple topics. Topics are ideal for news, sports, or interest-based notifications. You can also target users based on their behavior using Analytics audiences. The combination of topics and audiences enables powerful segmentation. Use the Firebase Console for simple topic management. Use the Admin SDK for programmatic topic management. Topics are automatically scaled for large audiences. Implement topic subscription management in your app. Allow users to choose which topics they want to receive.
// Subscribe a device to a topic await admin.messaging().subscribeToTopic(['device-token-1', 'device-token-2'], 'news'); // Unsubscribe await admin.messaging().unsubscribeFromTopic(['device-token-1'], 'news'); // Send to topic condition (AND/OR) const conditionMessage = { notification: { title: 'Exclusive Offer', body: 'Special discount for premium users', }, condition: "'premium' in topics && 'newsletter' in topics", }; await admin.messaging().send(conditionMessage);
Knowledge Check
Ready to test your understanding of 9. Cloud Messaging: Push Notifications & Engagement?