How to Send Notifications Using Firebase Functions
Use
Firebase Cloud Functions to trigger events and send notifications via Firebase Cloud Messaging (FCM). Write a function that listens to database or authentication events, then call admin.messaging().send() with the notification payload to deliver messages to devices.Syntax
The basic syntax involves creating a Firebase Cloud Function that triggers on an event, then using the Firebase Admin SDK to send a notification message.
functions.firestore.document('path').onCreate((snap, context) => { ... }): Trigger on Firestore document creation.admin.messaging().send(message): Sends a notification message.message: Object containingtokenortopicandnotificationdetails.
javascript
const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(); exports.sendNotification = functions.firestore.document('messages/{messageId}').onCreate((snap, context) => { const messageData = snap.data(); const payload = { notification: { title: messageData.title, body: messageData.body }, token: messageData.token }; return admin.messaging().send(payload); });
Example
This example shows a Firebase Cloud Function that sends a notification when a new Firestore document is created in the messages collection. The notification includes a title and body, and is sent to a specific device token.
javascript
const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(); exports.notifyNewMessage = functions.firestore.document('messages/{messageId}').onCreate(async (snap, context) => { const message = snap.data(); const payload = { notification: { title: message.title || 'New Message', body: message.body || 'You have a new message.' }, token: message.token }; try { const response = await admin.messaging().send(payload); console.log('Notification sent successfully:', response); return null; } catch (error) { console.error('Error sending notification:', error); return null; } });
Output
Notification sent successfully: projects/your-project-id/messages/1234567890
Common Pitfalls
- Missing device token: Notifications require a valid device token; ensure it is stored and passed correctly.
- Not initializing admin SDK: Always call
admin.initializeApp()before using messaging. - Incorrect payload format: The
messageobject must have correct keys likenotificationandtokenortopic. - Not handling async properly: Use
async/awaitor return promises to avoid function timeout.
javascript
/* Wrong: Missing admin.initializeApp() */ const functions = require('firebase-functions'); const admin = require('firebase-admin'); exports.badFunction = functions.firestore.document('messages/{id}').onCreate((snap) => { const message = snap.data(); const payload = { notification: { title: 'Hi' }, token: message.token }; return admin.messaging().send(payload); // Error: admin not initialized }); /* Right: Initialize admin SDK */ const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(); exports.goodFunction = functions.firestore.document('messages/{id}').onCreate(async (snap) => { const message = snap.data(); const payload = { notification: { title: 'Hi' }, token: message.token }; return await admin.messaging().send(payload); });
Quick Reference
Remember these key points when sending notifications with Firebase Functions:
- Initialize Firebase Admin SDK once per function file.
- Use triggers like Firestore, Realtime Database, or Authentication events.
- Prepare a
messageobject withnotificationandtokenortopic. - Return or await the
admin.messaging().send()promise to complete the function.
Key Takeaways
Initialize Firebase Admin SDK before sending notifications in Cloud Functions.
Use event triggers like Firestore document creation to send notifications automatically.
Send notifications by calling admin.messaging().send() with a proper message payload.
Always handle asynchronous calls with async/await or return promises to avoid errors.
Ensure device tokens are valid and included in the notification payload.