Firebase Cloud Messaging Device Tokens — Managing Push Notification Registration
In this tutorial, you will learn about Firebase Cloud Messaging Device Tokens. We cover key concepts, practical examples, and best practices to help you master this topic.
Firebase Cloud Messaging uses device registration tokens to deliver push notifications to specific devices. Managing token lifecycle and associating tokens with users is critical for reliable notification delivery.
What You'll Learn
- Obtaining FCM registration tokens
- Handling token refresh and expiration
- Storing and managing device tokens securely
Why It Matters
Invalid or expired tokens cause undelivered notifications. Proper token management ensures reliable delivery. DodaTech's alert system uses FCM tokens to send real-time security alerts to user devices.
flowchart LR
A["App starts"] --> B["Request notification permission"]
B --> C["Get FCM token"]
C --> D["Save token to Firestore"]
D --> E["Token refresh?"]
E -->|"Yes"| F["Get new token"]
F --> G["Update token in Firestore"]
E -->|"No"| H["Use existing token"]
G --> H
H --> I["Send notification via Admin SDK"]
Code Examples
// Web: Get FCM token
import { getMessaging, getToken, onMessage } from 'firebase/messaging';
import { messaging } from './firebase';
async function requestPermissionAndGetToken() {
try {
// Request notification permission
const permission = await Notification.requestPermission();
if (permission !== 'granted') {
throw new Error('Notification permission denied');
}
// Get FCM token
const token = await getToken(messaging, {
vapidKey: 'YOUR_VAPID_KEY'
});
console.log('FCM Token:', token);
return token;
} catch (error) {
console.error('Failed to get token:', error);
return null;
}
}
// Save token to Firestore
import { doc, setDoc, deleteDoc, collection } from 'firebase/firestore';
async function saveTokenToUser(userId, token) {
const tokenRef = doc(db, 'users', userId, 'devices', token);
await setDoc(tokenRef, {
token: token,
platform: 'web',
userAgent: navigator.userAgent,
createdAt: new Date(),
lastSeen: new Date()
});
}
async function removeToken(token) {
// Find and delete token document
const snapshot = await getDocs(
query(collection(db, 'devices'), where('token', '==', token))
);
snapshot.forEach(doc => deleteDoc(doc.ref));
}
// Handle token refresh and foreground messages
import { onTokenRefresh } from 'firebase/messaging';
// Listen for token refresh
onTokenRefresh(messaging, async (newToken) => {
console.log('Token refreshed:', newToken);
const user = auth.currentUser;
if (user) {
await saveTokenToUser(user.uid, newToken);
}
});
// Handle foreground messages
onMessage(messaging, (payload) => {
console.log('Foreground message:', payload);
showNotification(payload.notification.title, payload.notification.body);
});
// Admin SDK: Send notification to specific token
const admin = require('firebase-admin');
async function sendToDevice(token, title, body) {
const message = {
notification: { title, body },
token: token,
android: { priority: 'high' },
apns: { payload: { aps: { sound: 'default' } } }
};
try {
const response = await admin.messaging().send(message);
console.log('Successfully sent message:', response);
} catch (error) {
if (error.code === 'messaging/registration-token-not-registered') {
console.log('Token expired, remove from database');
await removeToken(token);
}
}
}
Common Mistakes
1. Not Handling Token Refresh
Tokens can change. Always listen for token refresh and update your database.
2. Storing Tokens Without User Association
Without user association, you cannot send targeted notifications.
3. Not Cleaning Up Expired Tokens
Unregistered tokens cause send errors. Remove them when FCM reports them as invalid.
4. Requesting Permission at App Start
Ask for notification permission in context, not immediately on app launch.
5. Ignoring Platform Differences
Token format and refresh behavior differ between web, Android, and iOS.
Practice Questions
- How do you get an FCM token in a web application?
- How do you handle token refresh?
- How should you store device tokens?
- How do you detect and remove expired tokens?
- What VAPID key is used for web push notifications?
Answers:
- Call getToken() from the Firebase Messaging SDK.
- Listen for onTokenRefresh and save the new token.
- Store in Firestore associated with the user and device.
- Handle the messaging/registration-token-not-registered error and remove the token.
- The VAPID key from the Firebase Console > Cloud Messaging > Web configuration.
Challenge: Build a notification system that requests permission, gets FCM tokens, stores them in Firestore, handles token refresh, sends notifications via Admin SDK, and cleans up expired tokens automatically.
FAQ
Mini Project
Build a push notification manager: register for FCM tokens, store in Firestore with user association, handle token refresh and cleanup, send test notifications via Admin SDK, and display notification history. Include a dashboard showing active devices per user.
What's Next
Learn about FCM topics for sending notifications to groups, then explore FCM campaigns for scheduled notifications.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro