Providing Firebase Admin SDK topic messaging example
Here's a concise Node.js example showing how to subscribe device tokens to a topic and send high-priority data messages using the Firebase Admin SDK. It includes subscribing tokens and sending a topic message with "priority": "high" for background wake-up.
Below is a minimal example in Node.js using the Firebase Admin SDK to:
- Subscribe device tokens to a topic
- Send a high-priority data message to that topic (so it can wake the app in the background, as long as the client handles background messages properly)
// 1. Install the Admin SDK if you haven't:
// npm install firebase-admin
const admin = require('firebase-admin');
// Initialize the Admin SDK (ensure you have your service account JSON)
admin.initializeApp({
credential: admin.credential.applicationDefault(),
// or admin.credential.cert(require('./serviceAccountKey.json'))
});
// Example: subscribe some FCM registration tokens to a topic
async function subscribeToTopic(tokens, topic) {
try {
const res = await admin.messaging().subscribeToTopic(tokens, topic);
console.log('Subscribed to topic:', res);
} catch (err) {
console.error('Error subscribing:', err);
}
}
// Example: send a high-priority data message to a topic
async function sendHighPriorityDataMessage(topic) {
const message = {
topic,
android: {
priority: 'high', // High priority for Android
notification: {
// Optional: if you want a display notification alongside data
title: 'Background Data Message',
body: 'This message can wake the app in the background.'
}
},
// For iOS, you might set apns headers similarly:
// apns: {
// headers: { 'apns-priority': '10' },
// payload: { aps: { contentAvailable: true } }
// },
// Pure data message (the client must handle this in the background):
data: {
customKey: 'customValue',
anotherKey: 'anotherValue'
}
};
try {
const res = await admin.messaging().send(message);
console.log('Message sent to topic:', res);
} catch (err) {
console.error('Error sending message:', err);
}
}
// --- Example usage ---
const myTopic = 'myTopicName';
// Replace with one or more valid FCM registration tokens
const deviceTokens = [
'YOUR_FCM_REGISTRATION_TOKEN_1',
'YOUR_FCM_REGISTRATION_TOKEN_2'
];
(async () => {
await subscribeToTopic(deviceTokens, myTopic);
await sendHighPriorityDataMessage(myTopic);
})();
Client-side notes
- Android (native): Handle background data messages in a
FirebaseMessagingService. When priority is set to high for Android and the payload includes data, the service can be triggered in the background.
- iOS: For “silent” data notifications, include
content-available: 1 and set the apns-priority to 10 or 5 depending on your use case, and handle it in your app’s background handler.
- Web: In the Service Worker (e.g.
firebase-messaging-sw.js), use onBackgroundMessage (or the older setBackgroundMessageHandler) to process data payloads in the background.
That’s all you need to subscribe tokens to a topic and send high-priority data messages that can wake your app in the background.