Dallas Dallas -4 years ago 128
Javascript Question

How to use batch notifications API with Cloud Functions for Firebase?

I'm just trying to have my app send a notification to the users when someone likes there event.

I have tried to do it this way:

exports.likeAddedNotification = functions.database.ref('/eventLikes/{eventID}/{userWhoLikedID}').onWrite(event => {
const userWhoLikedID = event.params.userWhoLikedID;
console.log("User has liked a post " + userWhoLikedID);

admin.database().ref('events/' + event.params.eventID).once('value').then(function(snapshot) {
var usersID = snapshot.val().userId;
console.log("The person who made the post is " + usersID);

//Send notification to that user
var payload = {
"group_id": "batch_push_sender",
"push_time": "now",
"message": {
"body": usersID + " liked your event"
"recipients": {
"custom_ids": [usersID]
"sandbox": true, // Only for iOS


console.log("Sent a notification to " + usersID);


(Sorry for including so much code, but I feel it may all be relevant)
If I use this code and remove the

var payload = ...



it works exactly how I'd expect. It will write to the console saying which post is liked and who liked that post.

I'm really not sure if the issue is coming from doing to much in a closure, or if I'm just doing something plain wrong, or if it's the Batch API that is causing errors.

If you know of a better site for push notifications that allows using a UDID as a custom identifier so that I don't have to manually deal with tokens for each device, please let me know!

Answer Source

First, make sure to return your Promises, that's the only way to guarantee that the Cloud Functions worker will keep things going. Since Firebase Cloud Notifications are sync, it's very likely your request is getting aborted.

You should also check out the Firebase Admin SDK's messaging components. We've built in some nice APIs for FCM. We have an example on how to use these in Cloud Functions for Firebase on GitHub https://github.com/firebase/functions-samples/tree/master/fcm-notifications

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download