Firebase Cloud Messaging Topics — Sending Targeted Push Notifications to Groups
In this tutorial, you will learn about Firebase Cloud Messaging Topics. We cover key concepts, practical examples, and best practices to help you master this topic.
FCM topics allow you to send push notifications to groups of devices that have subscribed to a specific topic, enabling targeted messaging without managing individual device tokens.
What You'll Learn
- Subscribing devices to topics
- Sending messages to topics
- Managing topic subscriptions
Why It Matters
Topics simplify group messaging. Instead of sending to hundreds of individual tokens, send once to a topic. DodaTech uses topics for channel-based alerts: security-critical, informational, and system notifications.
flowchart TD
A["Device subscribes to 'alerts' topic"] --> B["Topic: alerts"]
C["Device subscribes to 'updates' topic"] --> D["Topic: updates"]
E["Admin sends to /topics/alerts"] --> B
B --> F["All alert subscribers receive"]
E --x D["Updates subscribers not affected"]
Code Examples
// Client: Subscribe to a topic
import { getMessaging, subscribeToTopic, unsubscribeFromTopic } from 'firebase/messaging';
async function subscribeToAlerts(token) {
try {
await subscribeToTopic(token, 'security-alerts');
console.log('Subscribed to security-alerts topic');
} catch (error) {
console.error('Subscription failed:', error);
}
}
async function unsubscribeFromTopic(token) {
await unsubscribeFromTopic(token, 'security-alerts');
}
// Admin SDK: Send to topic
const admin = require('firebase-admin');
async function sendToTopic(topic, title, body, data = {}) {
const message = {
notification: { title, body },
data: data,
topic: topic,
android: { priority: 'high' },
apns: {
payload: {
aps: { sound: 'default', badge: 1 }
}
}
};
try {
const response = await admin.messaging().send(message);
console.log(`Sent to topic ${topic}:`, response);
return response;
} catch (error) {
console.error('Failed to send to topic:', error);
}
}
// Send to multiple topics with condition
async function sendToCondition() {
const message = {
notification: { title: 'Special Offer', body: 'Check it out!' },
condition: "'promotions' in topics && 'premium' in topics"
};
await admin.messaging().send(message);
}
// Manage subscriptions via Admin SDK
const admin = require('firebase-admin');
async function manageSubscription(token, topic, subscribe = true) {
try {
if (subscribe) {
await admin.messaging().subscribeToTopic(token, topic);
} else {
await admin.messaging().unsubscribeFromTopic(token, topic);
}
console.log(`${subscribe ? 'Subscribed' : 'Unsubscribed'} ${token} to ${topic}`);
} catch (error) {
console.error('Subscription management failed:', error);
}
}
// Batch subscribe multiple tokens
async function batchSubscribe(tokens, topic) {
const response = await admin.messaging().subscribeToTopic(tokens, topic);
console.log(`Success: ${response.successCount}, Failed: ${response.failureCount}`);
}
# Python Admin SDK: Topic messaging
import firebase_admin
from firebase_admin import messaging
# Send to topic
message = messaging.Message(
notification=messaging.Notification(
title='Security Alert',
body='Suspicious activity detected'
),
topic='security-alerts',
)
response = messaging.send(message)
print(f'Successfully sent: {response}')
# Subscribe/unsubscribe
tokens = ['token1', 'token2', 'token3']
response = messaging.subscribe_to_topic(tokens, 'security-alerts')
print(f'{response.success_count} tokens subscribed')
Common Mistakes
1. Creating Topics Dynamically from Clients
Topics should be predefined. Dynamic topics from clients can lead to topic sprawl.
2. Not Unsubscribing Old Tokens
When a token is refreshed, the old subscription is lost. Handle unsubscription on token change.
3. Using Too Many Topics
Keep topic count manageable. Too many topics fragment your audience.
4. Forgetting Topic Name Restrictions
Topic names must match ^[a-zA-Z0-9-_.~%]+$. Use descriptive names.
5. Not Handling Topic Subscription Failures
Network errors during subscription may leave devices unsubscribed. Retry on failure.
Practice Questions
- How do you subscribe a device to a topic?
- How do you send a notification to a topic?
- What is a topic condition?
- How do you batch subscribe multiple tokens?
- What are topic name restrictions?
Answers:
- Call subscribeToTopic with the FCM token and topic name.
- Set topic in the message object and send via Admin SDK.
- A boolean expression using 'in topics' syntax for complex targeting.
- Call subscribeToTopic with an array of tokens.
- Names must match ^[a-zA-Z0-9-_.~%]+$.
Challenge: Build a notification preference system where users can subscribe to different topics (alerts, updates, promotions). Implement topic subscription management, send targeted notifications via Admin SDK, and display user preferences.
FAQ
Mini Project
Build a topic-based notification system with user preference management. Implement subscribe/unsubscribe for multiple topics, send notifications to topics via Admin SDK, use conditions for complex targeting, and display notification history filtered by topic.
What's Next
Learn about FCM campaigns for scheduled and A/B tested notifications, then explore Firebase Remote Config for feature flags.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro