Skip to content
All essays
iOSJanuary 15, 20265 min

Firebase Cloud Messaging: Complete Push Notification Guide

Master Firebase Cloud Messaging for cross-platform push notifications with React Native, Firebase Admin SDK, and advanced targeting

Ü
Ümit Uz
Mobile & Full Stack Developer

Firebase Cloud Messaging (FCM) provides a reliable, battery-efficient way to send messages across platforms. With FCM, you can notify users of new messages, events, or updates, even when your app isn't running. This comprehensive guide covers everything from basic setup to advanced features.

Getting Started

Firebase Project Setup

  1. 1Create Firebase project at console.firebase.google.com
  2. 2Add your app (iOS/Android/Web)
  3. 3Download configuration files
  4. 4Copy Server Key from Project Settings

Installation

bash
npm install firebase-admin

Backend Setup

typescript
import admin from 'firebase-admin';

const serviceAccount = require('./firebase-service-account.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
});

export const messaging = admin.messaging();

Device Registration

Register Device Token

typescript
export async function registerDevice(userId: string, token: string) {
  await db.deviceTokens.create({
    data: {
      userId,
      token,
      platform: 'ios', // or 'android'
      createdAt: new Date(),
    },
  });
}

Sending Notifications

Basic Notification

typescript
export async function sendPushNotification(
  userId: string,
  notification: {
    title: string;
    body: string;
  }
) {
  const tokens = await db.deviceTokens.findMany({
    where: { userId },
  });

  const message = {
    notification,
    tokens: tokens.map(t => t.token),
  };

  const response = await messaging.sendMulticast(message);
  return response;
}

Best Practices

Respect User Preferences

typescript
export async function canSendNotification(
  userId: string,
  type: string
): Promise<boolean> {
  const prefs = await getNotificationPreferences(userId);

  if (!prefs[type]) return false;

  return true;
}

Conclusion

FCM provides a powerful platform for push notifications. Implement device token management, rich notifications, and respect user preferences for the best results.

Enjoyed this essay? Share it.

Related essays

Next essay
Apple Push Notification Service (APNs) Guide