Skip to content

Firebase Cloud Messaging Device Tokens — Managing Push Notification Registration

DodaTech Updated 2026-06-28 4 min read

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

  1. How do you get an FCM token in a web application?
  2. How do you handle token refresh?
  3. How should you store device tokens?
  4. How do you detect and remove expired tokens?
  5. What VAPID key is used for web push notifications?

Answers:

  1. Call getToken() from the Firebase Messaging SDK.
  2. Listen for onTokenRefresh and save the new token.
  3. Store in Firestore associated with the user and device.
  4. Handle the messaging/registration-token-not-registered error and remove the token.
  5. 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

How long do FCM tokens last?

FCM tokens can last indefinitely but may change when: the app is restored on a new device, the user clears browser data, or the app is re-installed.

Can a user have multiple device tokens?

Yes. A user logged in on multiple devices will have one token per device. Store them as separate documents.

What happens if I send to an expired token?

FCM returns a 404 or NotRegistered error. Catch this error and remove the token from your database.

How many tokens can I store per user?

There is no practical limit. Store tokens in a subcollection under the user document for scalability.

Do FCM tokens work in localhost development?

Yes, but you must use a VAPID key and ensure the browser supports push notifications.

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