How to Send Push Notifications to Multiple FCM Tokens in Node.js
f you're working with Firebase Cloud Messaging (FCM) and want to send push notifications to multiple devices at once, you'll be using the registration_ids
property.
Here’s a practical function using Node.js, that sends push notifications to multiple FCM tokens:
🔍 Explanation
-
params.title
¶ms.body
These are the notification title and body text that will appear on the device. -
params.data
Custom data you want to send along with the notification. This can include deep-linking information, IDs, or any payload your app might need. -
content_available: true
This flag enables background notifications (especially useful for iOS). -
priority: "high"
Ensures that the notification is delivered immediately (useful for time-sensitive notifications). -
sound: "default"
Plays the default notification sound on the device. -
message.registration_ids
-
This is an array of FCM device tokens (also called registration tokens).
-
We wrap it with
new Set()
and spread into an array to ensure no duplicate tokens are included in the request.
-
-
fcm.send(message)
Finally, we send the message using the FCM service. -
Error Handling
Any errors during the process are caught, logged, and returned.
✅ Usage Example
Here’s how you might call this function:
🚀 Notes
-
The
registration_ids
option allows you to send up to 500 device tokens in a single API request. -
If you have more than 500 tokens, you’ll need to split them into multiple requests.
-
Make sure you handle responses to remove invalid or expired tokens from your database!
Post a Comment