Cloud Functions Push Notifications
Instagram Firebase
Cloud Functions are rather powerful when it comes to triggering actions based on events that occur within Firebase. In today's lesson, we'll learn how to setup Firebase Tools CLI for the terminal, and initialize a Cloud Functions project. This requires that you have Node installed on your system and that npm is available on the command line. Once we are done setting up our project, we deploy the helloWorld function to Firebase and see how we can interact with it. Finally, we send a push notification through FCM using our FCM Token from last episode.

Comments (38)
GeminixClown
5 years ago
The difference about Brian and other teacher is, he is really teach us how to read the documentation and implemented in the real time, finally i figure out a little bit of logic behind firebase cloud function, thanks Brian...
Игорь Магурян
5 years ago
As I told many times... Brian is the top one.
Brian Voong
5 years ago
omair_34
5 years ago
Brian I keep getting this error after typing 'npm install -g firebase-tools'. It keeps asking me to install under root Administrator
rehannali
5 years ago
Install this command using sudo at the start of npm. Your command should look like sudo npm install -g firebase-tools.
omair_34
5 years ago
Thanks it worked !
Kenny Ho
5 years ago
Your comment was a life saver!!!!
diehard98
5 years ago
Hi, Brian Thanks for great courses. I have question about warning that I am seeing from Firebase. Billing account not configured. External network is not accessible and quotas are severely limited. Configure billing account to remove these restrictions So, I just wonder what is limitation for free tier user. Can I still send push notifications to multiple users and devices? I googled it and found some pricing here (https://firebase.google.com/pricing/) but it says Cloud Messaging (FCM) is free for Spark plan but Cloud Functions has limitations about number of executions. Also there is something about outbound networking is only for Google services only. Thank you!
Brian Voong
5 years ago
diehard98
5 years ago
Thank you. I looked at it and it seems like there are some limitations but I do not need to worry about for now. Maybe after app gets more than 1000 users, it may start to have some limitations on calls.
Laurent Maquet
5 years ago
Is terminal embedded by default in Atom or is this an external package ? If so, which package ? I tried to install terminal-plus, but I couldn't get it working properly..
Brian Voong
5 years ago
johnrm9
5 years ago
Try platformio-ide-terminal. It works for me!
Laurent Maquet
5 years ago
Thanks johnrm9. Finally, I got it working properly... ( despite of a big memory leak occuring sporadically). Maybe I should try platemformio-ide-terminal.
mattphelps
5 years ago
Hey guys, When I enter npm -g firebase-tools the terminal says it cannot find the module 'asynckit'. Does anyone know what this is or how to fix this? Cheers
mattphelps
5 years ago
I am running Node v6.11.1 Do you think this has something to do with it?
Brian Voong
5 years ago
tobitech
5 years ago
I'm getting this error in my cloud function log: TypeError: admin.messaging.sendToDevice is not a function I don't know why sendToDevice is not a function. I've updated the packages and still showing that error.
Brian Voong
5 years ago
tobitech
5 years ago
It worked, thanks
stonypig1
5 years ago
don't know why when i check the firebase document page, it tells me to use admin,messaging().send() without todevice, which didn't work for me, once i used your .sendtoDevice and it worked.
Obrac
5 years ago
Hey everyone, Have any of you come to the following errors? Unexpected function expression prefer-arrow-callback Each then() should return a value or throw promise/always-return Unexpected function expression prefer-arrow-callback I am basically stuck at the last step before testing the new push notifications with a title and body. I've tried both project source code and firebase sample code, both return the same errors. Any thoughts?
Damian Głasek
5 years ago
i have this same :((
Obrac
5 years ago
Hey Damian, I am not certain it is the right solution, I hope Brian can correct me if possible, however, I was able to correct this by simply adding the return. // Send a message to the device corresponding to the provided // registration token. admin.messaging().sendToDevice(userWeAreFollowing.fcmToken, payload) .then(response => { // See the MessagingDevicesResponse reference documentation for // the contents of response. console.log("LOGGER --- Successfully sent following message:", response); return true }) .catch(error => { console.log("LOGGER --- Error sending following message:", error); return true Hope it helps.
Damian Głasek
5 years ago
yes i find solution in internet :)) i add 'return response' but thx for answer :))
Obrac
5 years ago
can you post the block that is executing this so I can help out? Maybe there is a typo, trust me, I had my own.
stonypig1
5 years ago
don't know much about cloud function nor Node. Do we have to use firebase function to send remote notification ? can we use event listener, once a user got a fellower, we trigger the local notification. because i believe firebase function is very costly to use. (testing is free) can it(notification) be achieved by just using swift code in our app ? thanks
Brian Voong
5 years ago
stonypig1
5 years ago
thanks for clearing things up, now it makes so much sense
albaqawi
5 years ago
I am irritated on how the code on Firebase is outdated, they are moving fast and documentation is not up to speed in changes... in the code you will see they will have a token tag in the payload body...when I leave it there I get error: Error sending message: { Error: Messaging payload contains an invalid "token" property. Valid properties are "data" and "notification". so I am sharing my function to show how I just modified the code to send well. exports.helloWorld = functions.https.onRequest((request, response) => { response.send("Hello from Firebase WindowShopper!"); }); exports.sendPushNotifications = functions.https.onRequest((req, res) => { res.send("Attempting to send PUSH notification...") console.log("LOGGER: --- Trying to send PUSH message...."); //admin.message().sendToDevice(token, payload) // This registration token comes from the client FCM SDKs. var fcmToken = 'YOUR_TOKEN_FROM_LAST_EP'; // See documentation on defining a message payload. var payload = { notification: { title: "TITLE OF notification", body: "BODY OF MESSAGE" }, data: { score: '850', time: '2:45' }, }; // Set the message as high priority and have it expire after 24 hours. var options = { priority: "high", timeToLive: 60 * 60 * 24 }; // Send a message to the device corresponding to the provided // registration token. admin.messaging().sendToDevice(fcmToken, payload, options) .then((response) => { // Response is a message ID string. console.log('Successfully sent message:', response); return true }).catch((error) => { console.log('Error sending message:', error); return true }); })
Brian Voong
5 years ago
Chase McElroy
5 years ago
I'm trying the same code and I'm getting this error: ReferenceError: functions is not defined
Chase McElroy
5 years ago
I accidentally deleted the top lines: const functions = require('firebase-functions'); const admin = require('firebase-admin');
luoandre29
5 years ago
attaching working code if it helps anyone. make sure to run the below commands npm install firebase-functions@latest firebase-admin@latest --save npm install -g firebase-tools const functions = require('firebase-functions'); // The Firebase Admin SDK to access the Firebase Realtime Database. const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); exports.sendPushNotifications = functions.https.onRequest((req, res) => { res.send("Attempting to send push notifications"); console.log("LOGGER -- Trying to send push message"); // This registration token comes from the client FCM SDKs. var fcmToken = 'YOUR TOKEN HERE'; // See documentation on defining a message payload. var message = { notification: { title: "Push notification title HERE", body: "body HERE" }, data: { score: '850', time: '2:45' } }; // Send a message to the device corresponding to the provided // registration token. admin.messaging().sendToDevice(fcmToken,message) .then((response) => { // Response is a message ID string. console.log('Successfully sent message:', response); return response }) .catch((error) => { console.log('Error sending message:', error); throw new Error("Error sending message"); }); });
Yoel Lev
5 years ago
Thanks That was helpful. from some reason when i run npm install -g firebase-tools it is stuck in a loop, any ideas what could have gone wrong ?
Anirudh Bandi
5 years ago
thanks that was very helpful
esong2288
4 years ago
Anyone know if this still works? The documentation has changed and no matter what I try I still get "Each then() should return a value or throw promise/always-return" error. I can't tell if I'm copying something wrong or what I'm missing.
Brian Voong
4 years ago
esong2288
4 years ago
Unfortunately, I'm still getting the same error. Man, I really hate terminal work lmao
esong2288
4 years ago
For some reason even when it's just the helloWorld function I'm still getting the "Each then() should return a value or throw promise/always-return" error. Could it be something with my terminal?
Brian Voong
4 years ago
Share App
4 years ago
Thanks for code! Small thing, but I think I needed the space between the two here to work: "fcmToken, message"
stonypig1
5 years ago
npm and firebase CLI tool, we don't need to install them and put them in the same directory as our main project app file , right ? thanks
AndreaMich
5 years ago
i have a problem: when i try to enter firebase deploy --only functions: sendPushNotifications it works, and also helloWorld function works but when I open the firebase functions console I found the two functions but both with 0 executions, and if I open the Log screen, I don't find any log. So I don't understand if there I need some permission or something else. Moreover I cannot try to send a notification to my phone because now when I login the accounts Xcode prints as devide token: 32 bytes. I don't know why it do that, but notifications works, because if I try to send a message to everyuser it works.
Kenny Ho
5 years ago
if any of you guys have problems with the installation in terminal. Type in sudo npm install -g firebase-tools this should help you install! Credit to Rehanni (comment down below)
Kenny Ho
5 years ago
Anyone else getting an error at 24:56? Mine keep saying: Error: functions predeploy error: Command terminated with none-zero exit code1. Im also getting: 37:11 error Each then() should return a value or throw promise/always-return THIS IS DRIVING ME INSANE!!!!!!!! lmao
Kenny Ho
5 years ago
I SOLVED IT!!!!!! AFTER 4 LONG HOURS OF RESEARCH AND THE POWER OF GOOGLE! Here is the code. REMEMBER TO "RETURN NULL" admin.messaging().sendToDevice(token, payload) .then((response) => { // Response is a message ID string. console.log('Successfully sent message:', response); return null; }) .catch((error) => { console.log('Error sending message:', error); }); }) can't believe that 1 line of code literally fks up everything.
Kenny Ho
5 years ago
nvm luoandre29 solved it below and i didn't see.... make it instead of "return null" make it "return response" -_-
Yoda1221
5 years ago
Hi Brian! I have a little problem. I followed your instructions based on the video, but I received the following error message. Please help! i deploying functions Running command: npm --prefix "$RESOURCE_DIR" run lint > functions@ lint /Users/belamacbookpro15/Documents/Xcode/01_iPhone/SpoonRestaurants/functions > eslint . /Users/belamacbookpro15/Documents/Xcode/01_iPhone/SpoonRestaurants/functions/index.js 20:9 error Each then() should return a value or throw promise/always-return ✖ 1 problem (1 error, 0 warnings) npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! functions@ lint: `eslint .` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the functions@ lint script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! /Users/belamacbookpro15/.npm/_logs/2018-03-19T07_33_41_252Z-debug.log Error: functions predeploy error: Command terminated with non-zero exit code1
Brian Voong
5 years ago
Yoda1221
5 years ago
Thanks! It works!
h01m3s
5 years ago
If anyone init cloud function in unexpected folder, remember to move ".firebaserc" with "firebase.json" and "functions" to new folder. ".firebaserc" is hidden in MacOS, you might miss it. Otherwise you won't be able to deploy to remote server.
rebeloper
5 years ago
If anyone has issue of not receiving the notification, consult the console log in Firebase: Error sending message: { Error: Firebase Cloud Messaging API has not been used in project *********** before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/fcm.googleapis.com/overview?project=*********** then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry. Just go there and Enable the API.
Brian Voong
5 years ago
Polas Opel
5 years ago
i functions: preparing functions directory for uploading... Error: Error occurred while parsing your function triggers. Error: Failed to parse app options file: Error: ENOENT: no such file or directory, open '[object Object]' Does anyone know what the problem is?
dshawn
5 years ago
Hey Brian, for some reason I can not get this to work at all. This is exactly what i have in atom but it still will not work. / The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers. const functions = require('firebase-functions'); exports.helloWorld = functions.https.onRequest((request, response) => { response.send("Hello from Firebase"); }); exports.sendPushNotifications = functions.https.onRequest((req, res) => { res.send("Attempting to send push notification...") console.log("LOGGER --- Trying to send push message...") }) I have tried everything from typing it out, going to another video and typing it out, copying and pasting some of the code other people have posted that they said works, and even deleting everything down to the code i have above. I am typing out "firebase deploy --only functions:sendPushNotifications" and I get the " 38:11 error Each then() should return a value or throw promise/always-return" error, even though there isn't a then() in the code above. Any help on why this is happening would be greatly appreciated!
dshawn
5 years ago
Hey Brian, I had one more question about something that I am stuck on. I used the collection view to fetch the photos and videos on my phone but my app won't allow me to upload the vides to firebase because in the debugging console it prints "Error Domain=NSCocoaErrorDomain Code=257 "The file “IMG_7646.MOV” couldn’t be opened because you don’t have permission to view it." UserInfo={NSFilePath=/var/mobile/Media/DCIM/117APPLE/IMG_7646.MOV, NSUnderlyingError=0x1c06508c0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}", so basically I don't have permission to view it. However if instead of loading all the videos to my app and selecting the video from the collection view, I use the image picker controller to access the video file as well as its URL, I am able to upload the video file to firebase storage and database! Could you or anyone else help me solve this problem I am having? Thanks in advance!
dshawn
5 years ago
Hey Brian, I know you are probably busy but could you take a look at this questions when you get a chance please. Thanks.
annajorrman
5 years ago
Alright, I've read and tried all the so post "final version" of the atom code but none work. Could someone with working code please please post it or email it to me at simon.harrysson@gmail.com. Thank you so much!
PatrickVB
5 years ago
Hello! Can someone please post a working, undated code. My previous version is no longer working? (July 19th, 2018) Thank You in advance. -Patrick
Brian Voong
5 years ago
PatrickVB
5 years ago
Thank You so much for the quick response. I will take a look at the update Firebase 5 project. -Patrick
PatrickVB
5 years ago
This code failed when I ran it the first time. I added: return null; to line 47. The code compiles with 2-warnings: 43:11 warning Unexpected function expression prefer-arrow-callback 49:12 warning Unexpected function expression prefer-arrow-callback The Push Notification for "Following" still is not working? Thanks, -Patrick
esong2288
4 years ago
When you run (firebase init functions), how can you choose a different Firebase project. It seems that after the first time running it says (.firebaserc already has a default project, skipping), but what if you wanted to choose a different project?
Brian Voong
4 years ago
esong2288
4 years ago
So I currently have the functions folder and the firebase.json file within my /Users/ directory, can I just drag the folder and the file into the InstagramFirebase folder to have it within the /Desktop/InstagramFirebase/ directory or will it screw things up? Thanks for taking the time to respond to all my questions
flashtrend
4 years ago
I am not sure what to do at the 7:15 seconds part. Am I supposed to make a new folder inside my projects main folder, or am I doing firebase init from the main project folder, or am i making a completely new folder outside my main project? Can you explain exactly how to go through this step.
Brian Voong
4 years ago
flashtrend
4 years ago
thanks!
Alex Du
4 years ago
Hi Brian, how do you use terminal to open firebase login. In my Mac, it does not work properly
Brian Voong
4 years ago
Daniel Peach
4 years ago
Hey! using Terminate! I help maintain that on atom! Good choice:)
Brian Voong
4 years ago
Daniel Peach
4 years ago
Ah alright using the old one. For everyone else: platformio-ide-terminal is no longer maintained, checkout Terminate:)
Daniel Peach
4 years ago
Commented too soon lol
mao
4 years ago
I receive npm ERR message when I try to install Firebase cloud function from Terminal. ERR code: EACCES: permission denied, access '/usr/local/lib/node_modules' I followed the Nodejs to use Node version manager to install, but I still have the ACCES error message. I tried to change permission setting of /usr/local/... by using "sudo chown -R command but I got "operation not permitted".
malrhex
4 years ago
This doesn't work. latest err before final deployment says: npm ERR! code ELIFECYCLE npm ERR! errno 1
Brian Voong
4 years ago
malrhex
4 years ago
Any Plans for Conversion to Swift 5? I got some errors on the Grid vs List view btw & the refresh. Thanks in advance for the follow up. I've been learning a lot btw. I like how you explain the things. Keep it up! keep adding more content :)
Danielvgftv
4 years ago
admin.messaging().sendToDevice(fcmToken, payload) .then(function(response) { // See the MessagingDevicesResponse reference documentation for // the contents of response. console.log("Successfully sent message:", response); return response }) .catch(function(error) { console.log("Error sending message:", error); throw new Error("Error sending message"); }); });
jamalbenamor
3 years ago
Thanks!
Clint Larenz Nurse
4 years ago
So we HAVE to deploy notifications this way? We can’t just do it through Firebase like we did in the last lesson?
Clint Larenz Nurse
4 years ago
Anyone get this? Error: Error occurred while parsing your function triggers. ReferenceError: functions is not defined
Clint Larenz Nurse
4 years ago
Silly me... figured it out. Guess this late night of coding is taking a toll lol.....
Brian Voong
4 years ago
Clint Larenz Nurse
4 years ago
Can I delete some of my unnecessary comments?
Brian Voong
4 years ago
Clint Larenz Nurse
4 years ago
Please, feel free to dispose of any of my comments that I figure out the answer to. Don’t wana flood your section, although it doesn’t seem that active these days. I’ll be back of course for me. Thanks mate
Clint Larenz Nurse
4 years ago
Ok.. now I am getting this Error: Error parsing triggers: Cannot find module './apps' Btw my file is literally the exact same
Clint Larenz Nurse
4 years ago
NVM Again, figured it out.
vinniepelia
4 years ago
Hey Brian/Everyone, I had a look through the comments and no luck with this at all. Code is below which does not work. Any assistance would be awesome! ---- const functions = require('firebase-functions'); const admin = require('firebase-admin'); // Update 6/13/18 // If you are getting errors regarding initializeApp and credentials, try updating libraries: admin.initializeApp(); exports.helloWorld = functions.https.onRequest((request, response) => { response.send("Hello from Firebase LBTA!"); }); exports.sendPushNotifications = functions.https.onRequest((req, res) => { res.send("Attempting to send push notification...") console.log("LOGGER --- Trying to send push message...") var fcmToken = "MY TOKEN HERE"; var payload = { notification: { title: "Push notification TITLE HERE", body: "Body over here is our message body..." }, data: { score: "850", time: "2:45" } }; admin.messaging().sendToDevice(token, payload) .then((response) => { // Response is a message ID string. console.log('Successfully sent message:', response); return null; }) .catch((error) => { console.log('Error sending message:', error); }); })
Cabraham
4 years ago
Brian Voong i got this while fallowing video 44 minute 25 Abraham-MacBook-Pro:functions Abraham$ firebase deploy --only functions === Deploying to 'cloudsheetsapp'... i deploying functions Running command: npm --prefix "$RESOURCE_DIR" run lint > functions@ lint /Users/Abraham/Desktop/CloudSheetsBeep/functions > eslint . /Users/Abraham/Desktop/CloudSheetsBeep/functions/index.js 44:13 warning Unexpected function expression prefer-arrow-callback 44:13 error Each then() should return a value or throw promise/always-return 49:14 warning Unexpected function expression prefer-arrow-callback ✖ 3 problems (1 error, 2 warnings) 0 errors and 2 warnings potentially fixable with the `--fix` option. npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! functions@ lint: `eslint .` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the functions@ lint script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! /Users/Abraham/.npm/_logs/2019-08-11T19_36_38_285Z-debug.log Error: functions predeploy error: Command terminated with non-zero exit code1 Abraham-MacBook-Pro:functions Abraham$ Can you help me pass that problem ?
Brian Voong
4 years ago
Cabraham
4 years ago
nvm i made it work through this video some how. There are some few changes on the firebase but if you fallow them you can make it work ..
Cabraham
4 years ago
thanks for you answering Brian see you on the next video :)
Cabraham
4 years ago
this is one of the things that i had to add ... $ npm install firebase-admin --save
Brian Voong
4 years ago
Cinquain
4 years ago
That video was super lit
Avisa
3 years ago
Brian I can't find sendToDevice method in firebase doc, and I cant run it. I think I need updated method, the one you were teaching it's not working for me :(
Avisa
3 years ago
also I copy paste yours but still not working
Clint Larenz Nurse
3 years ago
Hey Brain, If I am using a new computer. Would I need to get permission again install the firebase tools in terminal? If so how? I am getting an error trying to run ```npm install -g firebase-tools```
jamalbenamor
3 years ago
Download this package first: https://nodejs.org/dist/v12.18.1/node-v12.18.1.pkg
wills_lbta
3 years ago
Hi all. Here is a list of updates that helps map the video to the latest firebase sdk: https://firebase.google.com/docs/functions/beta-v1-diff Several things have changed. Here are just a couple... - initialization old: admin.initializeApp(functions.config().firebase); - initialization new: admin.initializeApp(); - onCreate old: functions.database.ref('/path').onCreate((event) => { - onCreate new: functions.database.ref('/path').onCreate((snap, context) => { The link is also good for understanding Cloud Firestore vs Realtime Database implementation.
whitebeard
2 years ago
Hey brian, just wanted to say thank you for all the effort you put in in this. I purchased this, I believe two years ago and still using you as the base reference for anything i have questions about. Hope your all good man, healthy & happy. Cheers
HELP & SUPPORT