This is a comprehensive request about Firebase Cloud Messaging (FCM) using the Admin SDK. I need to provide:
- Setting up Firebase Admin SDK
- Subscribing device tokens to topics
- Sending high-priority data messages
- Handling background message reception
- Client-side setup for receiving messages
Let me create a complete guide with server-side and client-side code examples.
I'll cover:
- Node.js/Python server setup
- Subscribing devices to topics
- Sending topic messages with high priority
- Android client implementation
- iOS client implementation (if applicable)
- Handling background messages
- Best practices
Let me structure this comprehensively with multiple code examples.
Firebase Admin SDK Topic Messaging with High-Priority Data Messages
I'll provide a complete guide for server-side and client-side implementation.
1. Server-Side Setup (Node.js)
Install Dependencies
npm install firebase-admin dotenv
Initialize Firebase Admin
// firebase-admin-config.js
const admin = require('firebase-admin');
const fs = require('fs');
const path = require('path');
require('dotenv').config();
// Initialize Firebase Admin SDK
const serviceAccountPath = path.join(
__dirname,
process.env.FIREBASE_SERVICE_ACCOUNT_PATH
);
const serviceAccount = JSON.parse(
fs.readFileSync(serviceAccountPath, 'utf8')
);
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
projectId: process.env.FIREBASE_PROJECT_ID,
});
module.exports = admin;
Topic Subscription Manager
// topicManager.js
const admin = require('./firebase-admin-config');
class TopicManager {
/**
* Subscribe device tokens to a topic
* @param {string[]} deviceTokens - Array of device tokens
* @param {string} topic - Topic name
*/
static async subscribeToTopic(deviceTokens, topic) {
try {
if (!Array.isArray(deviceTokens)) {
deviceTokens = [deviceTokens];
}
// FCM allows max 500 tokens per request
const chunks = this.chunkArray(deviceTokens, 500);
for (const chunk of chunks) {
const response = await admin
.messaging()
.subscribeToTopic(chunk, topic);
console.log(
`Successfully subscribed ${response} devices to topic: ${topic}`
);
}
return {
success: true,
message: `Subscribed ${deviceTokens.length} devices to ${topic}`,
};
} catch (error) {
console.error('Error subscribing to topic:', error);
throw error;
}
}
/**
* Unsubscribe device tokens from a topic
* @param {string[]} deviceTokens - Array of device tokens
* @param {string} topic - Topic name
*/
static async unsubscribeFromTopic(deviceTokens, topic) {
try {
if (!Array.isArray(deviceTokens)) {
deviceTokens = [deviceTokens];
}
const chunks = this.chunkArray(deviceTokens, 500);
for (const chunk of chunks) {
const response = await admin
.messaging()
.unsubscribeFromTopic(chunk, topic);
console.log(
`Successfully unsubscribed ${response} devices from topic: ${topic}`
);
}
return {
success: true,
message: `Unsubscribed ${deviceTokens.length} devices from ${topic}`,
};
} catch (error) {
console.error('Error unsubscribing from topic:', error);
throw error;
}
}
/**
* Utility to chunk arrays
*/
static chunkArray(array, size) {
const chunks = [];
for (let i = 0; i < array.length; i += size) {
chunks.push(array.slice(i, i + size));
}
return chunks;
}
}
module.exports = TopicManager;
2. High-Priority Message Sender
// messageSender.js
const admin = require('./firebase-admin-config');
class MessageSender {
/**
* Send high-priority data message to topic
* Data messages wake up the app in the background
*/
static async sendHighPriorityDataMessage(
topic,
data,
options = {}
) {
try {
const message = {
data: this.validateAndFormatData(data),
android: {
priority: 'high',
ttl: options.ttl || 3600, // 1 hour
notification: {
clickAction: 'FLUTTER_NOTIFICATION_CLICK',
},
},
apns: {
headers: {
'apns-priority': '10', // High priority
},
payload: {
aps: {
'content-available': 1, // Wake up app in background
sound: 'default',
},
},
},
webpush: {
urgency: 'high',
},
topic: topic,
};
const response = await admin.messaging().send(message);
console.log('Successfully sent high-priority message:', response);
return {
success: true,
messageId: response,
message: `High-priority message sent to topic: ${topic}`,
};
} catch (error) {
console.error('Error sending high-priority message:', error);
throw error;
}
}
/**
* Send multicast high-priority data message to specific devices
*/
static async sendHighPriorityMulticast(
deviceTokens,
data,
options = {}
) {
try {
const message = {
data: this.validateAndFormatData(data),
android: {
priority: 'high',
ttl: options.ttl || 3600,
},
apns: {
headers: {
'apns-priority': '10',
},
payload: {
aps: {
'content-available': 1,
},
},
},
};
const chunks = this.chunkArray(deviceTokens, 500);
const results = [];
for (const chunk of chunks) {
const response = await admin
.messaging()
.sendMulticast({
...message,
tokens: chunk,
});
results.push(response);
console.log(`Sent to ${response.successCount} devices`);
console.log(`Failed: ${response.failureCount} devices`);
if (response.failureCount > 0) {
response.responses.forEach((resp, index) => {
if (!resp.success) {
console.log(`Failed token: ${chunk[index]}`);
console.log(`Reason: ${resp.error}`);
}
});
}
}
return {
success: true,
results: results,
message: `High-priority multicast sent to ${deviceTokens.length} devices`,
};
} catch (error) {
console.error('Error sending multicast message:', error);
throw error;
}
}
/**
* Send high-priority message with notification payload
*/
static async sendNotificationWithData(
topic,
title,
body,
data = {},
options = {}
) {
try {
const message = {
data: this.validateAndFormatData(data),
notification: {
title: title,
body: body,
},
android: {
priority: 'high',
ttl: options.ttl || 3600,
notification: {
sound: 'default',
clickAction: 'FLUTTER_NOTIFICATION_CLICK',
color: options.color || '#FF0000',
tag: options.tag || 'notification_tag',
},
},
apns: {
headers: {
'apns-priority': '10',
},
payload: {
aps: {
alert: {
title: title,
body: body,
},
'content-available': 1,
sound: 'default',
},
},
},
webpush: {
notification: {
title: title,
body: body,
icon: options.icon || '/icon-192x192.png',
},
data: {
...data,
},
urgency: 'high',
},
topic: topic,
};
const response = await admin.messaging().send(message);
console.log('Successfully sent notification with data:', response);
return {
success: true,
messageId: response,
};
} catch (error) {
console.error('Error sending notification with data:', error);
throw error;
}
}
/**
* Validate and format data payload (FCM requires string values)
*/
static validateAndFormatData(data) {
const formattedData = {};
for (const [key, value] of Object.entries(data)) {
// FCM only accepts string values
if (value === null || value === undefined) {
continue;
}
formattedData[key] =
typeof value === 'string' ? value : JSON.stringify(value);
// FCM has key/value size limits
if (formattedData[key].length > 4096) {
console.warn(
`Warning: Data value for key '${key}' exceeds 4KB limit`
);
}
}
if (Object.keys(formattedData).length > 100) {
throw new Error('Data payload cannot contain more than 100 keys');
}
return formattedData;
}
static chunkArray(array, size) {
const chunks = [];
for (let i = 0; i < array.length; i += size) {
chunks.push(array.slice(i, i + size));
}
return chunks;
}
}
module.exports = MessageSender;
3. Express API Routes
// routes/messaging.js
const express = require('express');
const router = express.Router();
const TopicManager = require('../topicManager');
const MessageSender = require('../messageSender');
// Subscribe devices to topic
router.post('/subscribe', async (req, res) => {
try {
const { deviceTokens, topic } = req.body;
if (!deviceTokens || !topic) {
return res
.status(400)
.json({
error:
'deviceTokens and topic are required',
});
}
const result = await TopicManager.subscribeToTopic(
deviceTokens,
topic
);
res.json(result);
} catch (error) {
res.status(500).json({
error: error.message,
});
}
});
// Unsubscribe devices from topic
router.post('/unsubscribe', async (req, res) => {
try {
const { deviceTokens, topic } = req.body;
if (!deviceTokens || !topic) {
return res
.status(400)
.json({
error:
'deviceTokens and topic are required',
});
}
const result = await TopicManager.unsubscribeFromTopic(
deviceTokens,
topic
);
res.json(result);
} catch (error) {
res.status(500).json({
error: error.message,
});
}
});
// Send high-priority data message to topic
router.post('/send-to-topic', async (req, res) => {
try {
const { topic, data, ttl } = req.body;
if (!topic || !data) {
return res
.status(400)
.json({ error: 'topic and data are required' });
}
const result = await MessageSender.sendHighPriorityDataMessage(
topic,
data,
{ ttl }
);
res.json(result);
} catch (error) {
res.status(500).json({
error: error.message,
});
}
});
// Send notification with data to topic
router.post('/send-notification', async (req, res) => {
try {
const { topic, title, body, data, options } = req.body;
if (!topic || !title || !body) {
return res.status(400).json({
error:
'topic, title, and body are required',
});
}
const result =
await MessageSender.sendNotificationWithData(
topic,
title,
body,
data || {},
options || {}
);
res.json(result);
} catch (error) {
res.status(500).json({
error: error.message,
});
}
});
// Send high-priority message to specific devices
router.post('/send-multicast', async (req, res) => {
try {
const { deviceTokens, data, options } = req.body;
if (!deviceTokens || !data) {
return res.status(400).json({
error: 'deviceTokens and data are required',
});
}
const result = await MessageSender.sendHighPriorityMulticast(
deviceTokens,
data,
options || {}
);
res.json(result);
} catch (error) {
res.status(500).json({
error: error.message,
});
}
});
module.exports = router;
4. Main Express App
// server.js
const express = require('express');
const cors = require('cors');
require('dotenv').config();
const app = express();
// Middleware
app.use(cors());
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ limit: '10mb' }));
// Routes
const messagingRoutes = require('./routes/messaging');
app.use('/api/messaging', messagingRoutes);
// Health check
app.get('/health', (req, res) => {
res.json({ status: 'Server is running' });
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error('Error:', err);
res.status(500).json({
error: err.message || 'Internal server error',
});
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
5. .env Configuration
FIREBASE_PROJECT_ID=your-project-id
FIREBASE_SERVICE_ACCOUNT_PATH=path/to/serviceAccountKey.json
PORT=3000
6. Client-Side: Android Implementation
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.fcmapp">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Firebase Messaging Service -->
<service
android:name=".services.MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
</manifest>
Firebase Messaging Service
// MyFirebaseMessagingService.kt
package com.example.fcmapp.services
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.app.NotificationCompat
import com.google.firebase.messaging.FirebaseMessaging
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import com.example.fcmapp.MainActivity
import com.example.fcmapp.R
import android.util.Log
class MyFirebaseMessagingService : FirebaseMessagingService() {
companion object {
private const val TAG = "FCMService"
private const val CHANNEL_ID = "high_priority_channel"
}
/**
* Called when message is received.
* This works for both: notification & data payload
*/
override fun onMessageReceived(remoteMessage: RemoteMessage) {
Log.d(TAG, "From: ${remoteMessage.from}")
// Data payload is always available
if (remoteMessage.data.isNotEmpty()) {
Log.d(TAG, "Message data: ${remoteMessage.data}")
handleDataMessage(remoteMessage.data)
}
// Notification payload
remoteMessage.notification?.let {
Log.d(TAG, "Notification: ${it.body}")
handleNotification(it)
}
}
/**
* Handle data message in foreground
* In background, system automatically shows notification if present
*/
private fun handleDataMessage(data: Map<String, String>) {
try {
val actionType = data["action"] ?: return
when (actionType) {
"sync_data" -> {
Log.d(TAG, "Syncing data from background: $data")
// Perform sync operations
syncData(data)
}
"update_app" -> {
Log.d(TAG, "App update available: $data")
// Handle app update
}
"location_update" -> {
Log.d(TAG, "Location update received: $data")
// Handle location update
}
else -> {
Log.d(TAG, "Received data: $data")
}
}
} catch (e: Exception) {
Log.e(TAG, "Error handling data message", e)
}
}
/**
* Handle notification message
*/
private fun handleNotification(notification: RemoteMessage.Notification) {
val title = notification.title ?: "Notification"
val body = notification.body ?: ""
showNotification(title, body)
}
/**
* Show notification
*/
private fun showNotification(title: String, body: String) {
createNotificationChannel()
val intent = Intent(this, MainActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
}
val pendingIntent = PendingIntent.getActivity(
this,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
val notification = NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle(title)
.setContentText(body)
.setSmallIcon(R.drawable.ic_notification)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.build()
val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(System.currentTimeMillis().toInt(), notification)
}
/**
* Create notification channel for Android O+
*/
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
CHANNEL_ID,
"High Priority Notifications",
NotificationManager.IMPORTANCE_HIGH
).apply {
description = "Receives high-priority messages"
enableVibration(true)
enableLights(true)
}
val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}
/**
* Perform background sync operations
*/
private fun syncData(data: Map<String, String>) {
// Example: Perform sync operations
val dataType = data["type"] ?: return
val payload = data["payload"] ?: return
// This could trigger a WorkManager job for long-running tasks
Log.d(TAG, "Syncing $dataType: $payload")
}
/**
* Called if InstanceID token is updated.
*/
override fun onNewToken(token: String) {
Log.d(TAG, "Refreshed token: $token")
// Send token to server
sendTokenToServer(token)
}
/**
* Send device token to server
*/
private fun sendTokenToServer(token: String) {
// TODO: Send token to your server for subscription management
Log.d(TAG, "Should send token to server: $token")
}
}
Activity Implementation
// MainActivity.kt
package com.example.fcmapp
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.google.firebase.messaging.FirebaseMessaging
import com.example.fcmapp.ui.theme.FCMAppTheme
class MainActivity : ComponentActivity() {
companion object {
private const val TAG = "MainActivity"
}
private val messaging = FirebaseMessaging.getInstance()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Request notification permission (Android 13+)
requestNotificationPermission()
setContent {
FCMAppTheme {
MainScreen(messaging)
}
}
}
private fun requestNotificationPermission() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
requestPermissions(
arrayOf(android.Manifest.permission.POST_NOTIFICATIONS),
1
)
}
}
}
@Composable
fun MainScreen(messaging: FirebaseMessaging) {
var deviceToken by remember { mutableStateOf("") }
LaunchedEffect(Unit) {
messaging.token.addOnCompleteListener { task ->
if (task.isSuccessful) {
deviceToken = task.result
Log.d("FCM", "Device Token: $deviceToken")
}
}
}
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
verticalArrangement = Arrangement.Center
) {
Text("Device Token:", style = MaterialTheme.typography.headlineSmall)
SelectionContainer {
Text(
text = deviceToken,
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
)
}
Spacer(modifier = Modifier.height(16.dp))
Button(
onClick = {
subscribeToTopic(messaging, "news")
},
modifier = Modifier.fillMaxWidth()
) {
Text("Subscribe to 'news' Topic")
}
Spacer(modifier = Modifier.height(8.dp))
Button(
onClick = {
unsubscribeFromTopic(messaging, "news")
},
modifier = Modifier.fillMaxWidth()
) {
Text("Unsubscribe from 'news' Topic")
}
}
}
private fun subscribeToTopic(messaging: FirebaseMessaging, topic: String) {
messaging.subscribeToTopic(topic)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Log.d("FCM", "Subscribed to $topic")
} else {
Log.e("FCM", "Failed to subscribe to $topic")
}
}
}
private fun unsubscribeFromTopic(messaging: FirebaseMessaging, topic: String) {
messaging.unsubscribeFromTopic(topic)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Log.d("FCM", "Unsubscribed from $topic")
} else {
Log.e("FCM", "Failed to unsubscribe from $topic")
}
}
}
7. Testing API Calls
# Subscribe devices to topic
curl -X POST http://localhost:3000/api/messaging/subscribe \
-H "Content-Type: application/json" \
-d '{
"deviceTokens": ["token1", "token2", "token3"],
"topic": "news"
}'
# Send high-priority data message to topic
curl -X POST http://localhost:3000/api/messaging/send-to-topic \
-H "Content-Type: application/json" \
-d '{
"topic": "news",
"data": {
"action": "sync_data",
"type": "articles",
"payload": "{\"count\": 5}"
}
}'
# Send notification with data
curl -X POST http://localhost:3000/api/messaging/send-notification \
-H "Content-Type: application/json" \
-d '{
"topic": "news",
"title": "Breaking News",
"body": "New article available",
"data": {
"articleId": "123",
"category": "tech"
}
}'
# Send multicast to specific devices
curl -X POST http://localhost:3000/api/messaging/send-multicast \
-H "Content-Type: application/json" \
-d '{
"deviceTokens": ["token1", "token2"],
"data": {
"action": "update_app",
"version": "2.0.0"
}
}'
8. Best Practices
// bestPractices.js
class FCMBestPractices {
/**
* Best Practices for Firebase Cloud Messaging
*/
/*
* 1. PRIORITY SETTINGS
* - Use 'high' priority for time-sensitive messages (data sync, urgent updates)
* - Use 'normal' priority for non-urgent messages
* - High priority messages consume more battery
*/
/*
* 2. DATA PAYLOAD OPTIMIZATION
* - Keep data payloads small (< 4KB per key)
* - Use string values only
* - Maximum 100 keys per message
* - Compress large payloads with gzip if needed
*/
/*
* 3. BACKGROUND PROCESSING
* - Use Android WorkManager for long-running tasks
* - FCM has 10-second timeout for onMessageReceived()
* - Schedule jobs for heavy processing
*/
/*
* 4. TESTING
* - Test with both foreground and background app states
* - Verify battery usage with high priority messages
* - Monitor failure rates and invalid tokens
*/
/*
* 5. ERROR HANDLING
* - Handle invalid tokens gracefully
* - Implement retry logic with exponential backoff
* - Remove invalid tokens from subscription lists
*/
/*
* 6. FREQUENCY & RATE LIMITING
* - Implement rate limits for messages per device
* - Avoid sending duplicate messages
* - Use topic subscriptions instead of direct tokens for large groups
*/
/*
* 7. SECURITY
* - Use service account keys securely
* - Never expose keys in client-side code
* - Validate messages on client before processing
* - Use HTTPS for all API calls
*/
/*
* 8. MONITORING & ANALYTICS
* - Track delivery rates
* - Monitor error rates
* - Use Firebase Analytics for engagement metrics
* - Set up alerts for failure spikes
*/
static async exampleWithRetry(operation, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await operation();
} catch (error) {
if (i === maxRetries - 1) throw error;
const delay = Math.pow(2, i) * 1000; // Exponential backoff
console.log(`Retry ${i + 1} after ${delay}ms`);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
}
module.exports = FCMBestPractices;
9. Complete docker-compose.yml (Optional)
version: '3.8'
services:
fcm-server:
container_name: fcm-messaging-server
build:
context: .
dockerfile: Dockerfile
ports:
- "3000:3000"
environment:
- NODE_ENV=development
- FIREBASE_PROJECT_ID=${FIREBASE_PROJECT_ID}
- FIREBASE_SERVICE_ACCOUNT_PATH=/app/config/serviceAccountKey.json
- PORT=3000
volumes:
- ./config:/app/config
- ./src:/app/src
networks:
- fcm-network
restart: unless-stopped
networks:
fcm-network:
driver: bridge
Key Features Implemented:
✅ Topic Subscription Management - Subscribe/unsubscribe devices
✅ High-Priority Messaging - Wake up apps in background
✅ Data Payload Handling - Structured data with proper validation
✅ Multicast Support - Send to multiple devices efficiently
✅ Android Integration - Full implementation with Kotlin
✅ Background Processing - Handle messages when app is closed
✅ Error Handling - Graceful failure management
✅ Retry Logic - Exponential backoff for resilience
This complete solution provides production-ready Firebase Cloud Messaging with high-priority topic messaging!