Header Ads

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:

export const sendPush = async (params: any) => { try { let message: any = {}; // Set up the notification payload message.notification = { title: params.title, // Notification title body: params.body, // Notification body data: params.data, // Additional custom data content_available: true, // Enable background notifications priority: "high", // High priority for immediate delivery sound: "default", // Default notification sound }; // Additional data payload (optional) message.data = params.data; // Deduplicate tokens to avoid sending multiple times to the same device message.registration_ids = [...new Set(params.token)]; // Send the notification via FCM return await fcm.send(message); } catch (err) { // Log and return any errors logger.logger.error(err); return err; } };

🔍 Explanation

  • params.title & params.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:

await sendPush({ title: 'New Offer!', body: 'Check out our latest discounts.', data: { offerId: '1234' }, token: [ 'fcm_token_1', 'fcm_token_2', 'fcm_token_3', // ...more tokens ], });

🚀 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!

No comments

If you have any doubt, please let me know.

Powered by Blogger.
Weekly
Tech Updates