Lesson 20 / 25

Cloud Messaging (Push) Overview

Notifications to devices and browsers.

Tokens, permissions and server sends

Firebase Cloud Messaging (FCM) delivers notifications and data messages to Android, Apple and web clients. The client asks the user for notification permission and obtains a registration token (on the web with getToken, a VAPID key and a service worker such as firebase-messaging-sw.js); store the token against the user in Firestore. Your server (a Cloud Function or backend using the Admin SDK) sends messages to a token, a topic or a condition. Tokens expire or become invalid, so remove ones that fail with unregistered errors. Delivery is not guaranteed and platform rules (iOS, browsers) apply; check the docs.

Getting a token and sending

Client and Admin SDK, TypeScript.

// client
import { getMessaging, getToken, onMessage } from "firebase/messaging";

const messaging = getMessaging(app);
export async function enablePush(uid: string) {
  if ((await Notification.requestPermission()) !== "granted") return;
  const token = await getToken(messaging, { vapidKey: "PUBLIC_VAPID_KEY" });
  await setDoc(doc(db, "users", uid, "fcmTokens", token), { createdAt: serverTimestamp() });
}
onMessage(messaging, (payload) => showToast(payload.notification?.title));

// server (Admin SDK)
import { getMessaging as adminMessaging } from "firebase-admin/messaging";

export async function notify(token: string) {
  await adminMessaging().send({
    token,
    notification: { title: "New reply", body: "Someone answered your question." },
  });
}

A postal address for each device

The registration token is a mailing address; your server mails to it, and when the device moves away the address stops working and should be removed.

Quick check: Who should send FCM messages to other users' devices?

  • Any client directly with the web config
  • Trusted server code using the Admin SDK
  • Security Rules
  • Remote Config
Answer

Trusted server code using the Admin SDK — Sending requires server credentials.