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
- 1Create Firebase project at console.firebase.google.com
- 2Add your app (iOS/Android/Web)
- 3Download configuration files
- 4Copy Server Key from Project Settings
Installation
bash
npm install firebase-adminBackend 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.