User Follow Cloud Trigger
Instagram Firebase
In today's lesson, we set up a Cloud Function that will be observing for events whenever users are being followed in the Realtime Database. In order for these triggers to work, we create another Cloud Function that listens on the appropriate path. Finally, with these functions, we can figure out which users belong to which id. Once we obtain the necessary usernames and fcmToken properties, we can send out a notification with the correct messaging.

Comments (25)
Игорь Магурян
5 years ago
Hi, Brian. Took a look at your series of videos about setting notifications with FCM. Thank you very much for this material, it is super usefull... I received a lot of new information. I guess you can finish up this course with the last video, how to handle notification tap in different device states. Thanks again.
Brian Voong
5 years ago
wasim
5 years ago
Thanks Brain, I just finished the updated videos. When are you planing to release the new videos for pagination using firebase could functions?
Brian Voong
5 years ago
wasim
5 years ago
thanks, I really appreciate your effort.
kmignt
5 years ago
Hi Brain, great video but you didn't show how to go to the user who did the following (how to go to his profile). In the pre-video of push notification you showed this logic, but it's not in the tutorials. Are you going to do it as well? Thanks!
Brian Voong
5 years ago
kmignt
5 years ago
Thanks man, you're the best!
wasim
5 years ago
Hi brain, I just implemented cloud trigger in my project to send push notifications. It works for me.. but I still see an error for not sending back a promise or something. here's my code for (var playerUid in players) { admin.database().ref('/users/' + playerUid ).once('value', snapshot => { var data = snapshot.val(); var userFCM = data["fcm"]; console.log("userFCM: ", userFCM); var payload = { notification: { title: title, body: body }, data: { groupId: groupId } }; admin.messaging().sendToDevice(userFCM, payload) .then(response => { console.log("Successfully sent message:", response); }).catch(function(error) { console.log("Error sending message:", error); }); }) } I have checked an answer for similar problem here https://stackoverflow.com/questions/47743082/waiting-for-a-foreach-to-finish-before-return-from-my-promise-function but still I couldn't implement it, can you please help me? I am stuck here for long time
Brian Voong
5 years ago
wasim
5 years ago
thanks for your reply, I'll try to figure it out.. if I succeed, I'll place it here
diehard98
5 years ago
Hi, Brian Thanks for great courses. I was trying to get sound when I receive push notification from firebase as well and I found that I just need to add one more information in payload like below to play default 'ding' sound when user receives push notification in index.js file's cloud function. var payload = { notification: { title: notificationTitle, body: notificationMessage, sound: 'default' } }; Hope this helps someone else who is trying to play sound. :) Thanks!
stonypig1
5 years ago
it does, thanks so much for sharing it. do you figure out how to use different sound ? if you do please share , thanks
ahmadiah
5 years ago
Hi Brian, I am facing a problem when I am trying to fetch token from Firebase. Here is a link to my question in StackOverFlow: https://stackoverflow.com/questions/48056087/cloud-functions-error-firebase
ahmadiah
5 years ago
No worries I think I found the problem. I had the wrong path
veryDIMM
5 years ago
Hey Brian, I know this is a lot to ask but, can you please send me the index.js code modified so it works for the Firebase Messaging app. I have tried soooooo much but something isn't working... thanks SOOOOO much if you can get back to me.
Yoda1221
5 years ago
Hi Brian! I like your videos, I've almost learnt everything from them! And I also appreciate you explain everything step by step. I would like to ask a question: how can I send a message to all of the users, when for e.g. there is something new in the application? Thanks
Brian Voong
5 years ago
Anirudh Bandi
5 years ago
when I execute the observeFollowing function (08:56) I get this error TypeError: Cannot read property 'uid' of undefined at exports.observeFollowing.functions.database.ref.onCreate.event (/user_code/index.js:14:25) at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27) at next (native) at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71 at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12) at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36) at /var/tmp/worker/worker.js:700:26 at process._tickDomainCallback (internal/process/next_tick.js:135:7) so I comment those lines out and just print out "event" in the logs: I get the followin app: FirebaseApp { firebaseInternals_: FirebaseNamespaceInternals { firebase_: [Object], serviceFactories: {}, apps_: [Object], appHooks_: {} }, services_: {}, isDeleted_: false, name_: '__admin__', options_: { projectId: 'instagramfirebase-!@#$%', databaseURL: 'https://instagramfirebase-!@#$%.firebaseio.com', storageBucket: 'instagramfirebase-!@#$%.appspot.com', credential: [Object] }, INTERNAL: FirebaseAppInternals { credential_: [Object], isDeleted_: false, tokenListeners_: [] } }, instance: 'https://instagramfirebase-!@#$%.firebaseio.com', _path: '/following/8KCjOPXBsdM9LikaAcGQHKV4dDF3/NkMaql9RAhM4titj5hPJl68Q5zb2', _data: 1 } the _path variable has the correct info both uid and following followingId i dont know why the wild card variables arent working
Anirudh Bandi
5 years ago
when I log event.params "undefined" is printed
Anirudh Bandi
5 years ago
Modified the function this way It's working now.. exports.observeFollowing = functions.database.ref('/following/{followerId}/{followingId}').onCreate( (data,context) => { //let's logout some messages var followerId = context.params.followerId; var followingId = context.params.followingId; console.log('User: ' + followerId + 'is following: ' + followingId); })
annajorrman
5 years ago
THANK YOU SO MUCH! Anirudh Bandi you're a hero!
annajorrman
5 years ago
Brian too of course (:
yoowinks
5 years ago
Big thank you from me too, Anirudh.
tetraprism95
5 years ago
For those of you who can't seem to retrieve the firebase log result of for example, 'User: sxca9123913 following n1o23102', I'd suggest inside the observeFollowing function rewrite the code to return event.data.ref.root.child('User: ' + uid + ' is following: ' + followingId); . This will definitely work as its retrieving inside the database to get that information instead of returning uid of undefined.
tetraprism95
5 years ago
Help, I am getting the message successfully but not the notification. Any reason why that is? exports.observeFollowing = functions.database.ref('/following/{uid}/{followingId}').onCreate((data, context) => { var uid = context.params.uid; var followingId = context.params.followingId; // lets log out some messages // return event.data.ref.root.child('User: ' + uid + ' is following: ' + followingId)) console.log('User: ' + uid + ' is following: ' + followingId); admin.database().ref('/users/' + followingId).once('value', snapshot => { var userWeAreFollowing = snapshot.val(); var message = { notification: { title: "following", body: "following" }, token: userWeAreFollowing.fcmToken }; return admin.messaging().send(message) .then((response) => { console.log('Successfully sent message:', response); return response }) .catch((error) => { console.log('Error sending message:', error); }); }) })
edison1
5 years ago
This wasn't working when I did it. Now it just randomly worked.. without fixing anything,.. howw
edison1
5 years ago
has anyone been able to figure out how to block users with our database structure? i feel that re-writing the security is the way to go, but I'm not too sure. Any help would be hugeeeee
AndreaMich
5 years ago
Hi guys, Firebase has change different things with the last migration to the new beta so if anyone need the new code this, at least for me, works. Before paste the code run these three line on the terminal: npm install firebase-functions@latest --save npm install firebase-admin@5.11.0 --save npm install -g firebase-tools now you can paste the code: exports.observeFollowing = functions.database.ref('/following/{uid}/{followingId}') .onCreate((snapshot, context) => { const original = snapshot.val(); var uid = context.params.uid var followingId = context.params.followingId console.log('User: ', uid, 'is following ', followingId); // lets log out some messages admin.database().ref('/users/' + followingId).once('value', snapshot => { var userWeAreFollowing = snapshot.val(); admin.database().ref('/users/' + uid).once('value', snapshot => { var userDoingTheFollowing = snapshot.val(); var payload = { notification: { title: "You have a new follower", body: userDoingTheFollowing.username + ' is now following you', sound: 'default' }, data: { followerId: uid } } admin.messaging().sendToDevice(userWeAreFollowing.fcmToken, payload) .then((response) => { console.log('Successfully sent message:', response); return response }) .catch((error) => { console.log('Error sending message:', error); }); }) }) });
chrisggg
5 years ago
Thank you very much! This code made my notifications work . I think I had to update my firebase.
Kevin Liu
3 years ago
Thank you! This helped me out as well. :-)
Jaylon22
4 years ago
Hi brian, I love your videos they are very awesome, i was wondering if i wanted to send a notifications for likes to users. I notices that the likes node for our firebase does not have the user that posted to picture. It only has the postId and the user that like the photo. Is there a way i can access who posted the picture inside of a "observeLikes" function or would i have to restructure the like function from inside the app to include the user somehow? Thank you and have a bless day.
Brian Voong
4 years ago
Jaylon22
4 years ago
Hey Brian, I hope you are having a good December, and just had a quick question. I actually was able to figure out how to trigger a function when a user likes the post. Which i am actually proud of myself for doing, but when it comes to tapping the notification to go to the post i am kind of lost. I used this to get the post id, however i don't know how to get a snapshot.val() like you did the /users/ to get the uid of the person. Would i do this to get the specific postId return admin.database().ref('/posts/following' + postId).once('value', snapshot =>{ }) Or would i use something else to find the specific post?
Calist0
4 years ago
Hi guys, I'm stuck here and am sure you guys can help me. I'm kind of new to working with firebase and have a chat app that's not getting messages while the app is not running. My firebase tree is more like below: /messages fromId: "*****" messageUID: "****" seen: false status: "Delivered" text: "****" timestamp: *** toId: **** and I also have the following: /user-messages: user-messages 17w*****nOTzXXfSJ*****121 (this should be current user uid) -LRm*****kPquM0vYfh (recipient or chat partener uid) metaData badge: 0 isGroupChat: false lastMessageID: "****" userMessages -LRmb******AIlEZ97q: 1 So I just wanna know which path I should use between the 2, /messages or user-messages and what do I fetch from whichever path that's the best? I kind of tried several ways but am not getting the best way to approach this. exports.observeMessages = functions.database.ref('/????/{????}/{???}') .onCreate(event => { var *** var*** console.log( ); })
kestelle
4 years ago
Hello, did you ever figure this out, it would help very much, thanks!
Jaylon22
4 years ago
Hey Brian, I'm really enjoying the course quick question, if i wanted to the caption of the post and put it in the push notification for comments. How would i get the caption like you got the username of the user? I tried using this return admin.database().ref('/posts/{followingId}/' + postId).once('value', snapshot =>{ var postWeAreCommenting = snapshot.val(); For comments put it says that the caption is null, do you know a good way that i can fetch that post information to retrieve the caption?
Brian Voong
4 years ago
Jaylon22
4 years ago
No its returning "null" im not sure if i am if i am diving in correctly as for as syntax, maybe i'm mispelling but i'm not sure. Or it may not need the brackets, could that be a issue?
Brian Voong
4 years ago
Jaylon22
4 years ago
Great I’ll try to dig deep to see if I can get more info to receiving information about the post.
larryl
4 years ago
Fcmtoken is based on the device? so what if the user signs into another phone? I was thinking we can update the fcmtoken every time we log in but if we do that then only one of the two phones we are logged in will get the notification! also if we log into a phone that was previously logged in by another user in the app, then both user will get each others notification! how do i solve this problemm?
Brian Voong
4 years ago
Jaylon22
4 years ago
Hey Brian, Quick question is there a way i can send a firebase cloud message to multiple users device, think of it in a group chat tap of way? Would there be any documentation to refer to. Thank you in advance.
mao
4 years ago
I followed AndreaMich's code and the observeFollowing cloud function works. However, there is no sound on the receiver's end when receiving the notification. When I did the manual cloud messaging. The sound works fine, but it doesn't work in cloud function.
Kamil Michalik
3 years ago
comment out sound: 'default' in function if you want default sound in push notification
petar7
4 years ago
Hi Brian do you have any idea how to pull autoID generated by childbyAutoId() , example when I have list of items because Firebase does not update same value fcm does not work when same value overwritten is
Cinquain
4 years ago
One of the best videos from Brian
jamalbenamor
3 years ago
This is so helpful!
dannyp75
2 years ago
Is there a way to add user photo into the payload just like sound?
Brian Voong
2 years ago
dannyp75
2 years ago
Thanks Brian, I came across documentation for pics and was hopeful. Let me find the link
dannyp75
2 years ago
Brian, I came across this in the Firebase documentation. https://firebase.google.com/docs/cloud-messaging/ios/send-image
HELP & SUPPORT