Getting Started with Cloud Functions for Firebase - Firecasts

By: Firebase

726   16   48543

Uploaded on 04/11/2017

Sample code:

Cloud Functions for Firebase lets you run managed backend code for your mobile app that extends and connects Firebase features. In this Firecast, Jen will show you how to get your computer set up for development and deploy your first function.

Add the Firecasts playlist!

Subscribe to the brand new Firebase Channel:

Music by

Comments (14):

By anonymous    2017-09-20

since there is Firebase Functions (Firebase Introduction ), you can use NodeJS to create PDfs for example with the pdfkit(PDFKit). The following example descirbes a way to generate an PDF on AccountCreation(Event), save it to the storage and send it to the user via mail. All this Happens on the Firebase Server. For all used Librarys dont forget to npm install them and include them to the package.json. A tricky part is to add the Firebase Admin SDK to your Server. Also, this helped a lot. To be honest this took me some hours. So dont hestiate to ask for details!

const functions = require('firebase-functions');
const admin = require("firebase-admin");

const nodemailer = require('nodemailer');
const pdfkit = require('pdfkit');

const gmailEmail = ''
const gmailPassword = 'test123.ThisisNoTSave'
const mailTransport = nodemailer.createTransport( `smtps://${gmailEmail}:${gmailPassword}`);

const serviceAccount = require("./youradminsdk.json");
//Save this file to your functions Project

// Your company name to include in the emails
const APP_NAME = 'My App';
const PROJECT_ID = "google-testproject";

    credential: admin.credential.cert(serviceAccount),
    databaseURL: `https://${PROJECT_ID}`,
    storageBucket: `${PROJECT_ID}`

var config = {
    projectId: `${PROJECT_ID}`,
    keyFilename: './youradminsdk.json'

const storage = require('@google-cloud/storage')( config);
const datastore= require('@google-cloud/datastore')(config);

// [START onCreateTrigger]
exports.sendPDFMail = functions.auth.user().onCreate(event => {
// [END onCreateTrigger]

       // [START eventAttributes]
       const doc = new pdfkit;
       const user =; // The Firebase user.
       const email =; // The email of the user.
       const displayName = user.displayName; // The display name of the user.
       // [END eventAttributes]

       const bucket = storage.bucket(`${PROJECT_ID}`); 
       const filename = + 'output.pdf';                       
       const file = bucket.file(filename);
       const stream = file.createWriteStream({resumable: false});

      // Pipe its output to the bucket
       doc.fontSize(25).text('Some text with an embedded font!', 100, 100);           
       stream.on('finish', function () {                   
             return sendPDFMail(email, displayName, doc);

       stream.on('error', function(err) {
    // [END sendPDFMail]

    // Sends a welcome email to the given user.
    function sendPDFMail(email, displayName, doc) {
        const mailOptions = {
            from: '"MyCompany" <>',
            to: email,        

        mailOptions.subject = `Welcome to ${APP_NAME}!`;
        mailOptions.text = `Hey ${displayName}!, Welcome to ${APP_NAME}. I hope you will enjoy our service.`;
        mailOptions.attachments =  [{filename: 'meinPdf.pdf', content: doc, contentType: 'application/pdf'  }];        

        return mailTransport.sendMail(mailOptions).then(() => {
            console.log('New welcome email sent to:', email);

Original Thread

By anonymous    2017-09-20

This is a great use case for Cloud Functions for Firebase.

You can write functions that trigger when data is added to the database and when a new user is authenticated for the first time. Here are some resources to find out more:

Cloud Functions for Firebase Usage Guide

Cloud Functions for Firebase samples

Getting Started with Cloud Functions for Firebase - Firecasts

Database Triggers with Cloud Functions for Firebase - Firecasts

Authentication Triggers with Cloud Functions for Firebase - Firecats

The Cloud Functions for Firebase samples are especially useful because they include how to send emails using Nodemailer.

Original Thread

By anonymous    2017-09-20

Rather than retrieving the data and downloading it to the client, I recommend using Cloud Functions for Firebase. That way, the data remains private and can be processed quickly. See an answer I gave to this question before here.

Also check out these resources to get started with Cloud Functions for Firebase:

Cloud Functions for Firebase Usage Guide

Cloud Functions for Firebase samples

Getting Started with Cloud Functions for Firebase - Firecasts

Original Thread

By anonymous    2017-09-23

No, you would only need to run a local web server for development if you are creating a website, and even then, it isn't necessary. What I would recommend is studying and learning the Firebase Functions commands and write a few commands for that. You can view a video made by the Firebase team here:, and the docs page is in my answer above. Hope this helps!

Original Thread

By anonymous    2017-10-01

Initially, Firebase did not have a feature to implement server-side processing/calculations. All your processing had to be done on the client side.

Now, they've recently introduced a new feature called Cloud Functions For Firebase. Its a really useful new addition where you can write server-side code without the hassles of managing servers or instances. Read up more about it from the above link.

Also, this Youtube playlist by Jen Person is a great start. And, you can find examples similar to your use case here.

Original Thread

By anonymous    2017-12-18

Top two reasons for using Firebase:

  1. You want your users to have option to login with any social media platform but do not want separate dashboards since its hard to get proper analytics.
  2. Firebase has introduced something amazing called cloud functions which will allow to have your server side script to be hosted on Firebase. You would generally want the token given to you through authentication to be stored in your server and database. Firebase is now providing both so having everything in the same place does help. I basically brought down the release time for a decently complicated app from 14 days to 6 days using a combination of these two.

Original Thread

By anonymous    2017-12-18

Finally found the solution after struggling for almost 1 month.

These are the basic steps

  1. Firs off all you need to make sure that you have an active apple developers account

  2. just enable firebase push notifications here ie the link of youtube video for this step

  3. Now your app is set up for firebase remote notifications but we can only trigger them from the firebase console so here is the tricky part. here is the link of video to enable firebase console on your mac
  4. for the first time it will be good to see this video too because in this video they'll learn to write code in node.js and deploy it to the firebase.
  5. Now if anyone wants to make an API instead of making a trigger then here is a code of API which sends the notification to other user by getting his FCM token from the firebase... You can modify it according to your need

i am finding it difficult to post code in its exact form but the code starts from here

const functions = require('firebase-functions');

const admin =require('firebase-admin');

const ref=admin.database().ref();
exports.sendNotification=functions.https.onRequest((req,res) =>{

    const id =
    const title = req.query.title
    const message = req.query.message
    const key = req.query.key
    // admin.database.ref()

    const payload ={

        notification: {
            title: title,
            body: message,
            //badge: '1',
            sound: 'default',

    console.log('Param [key] is '+key);

    const keys = [] ;

    .then(snap => {
        snap.forEach(childSnap => {

            const loopKey=childSnap.val().key;


        return keys;

        //console.log('Keys in database : '+keys.join());

            if(!key || !id || !message)
                res.status(400).send('Bad request');
                .then(snapshot => {
                    if (snapshot.val()){
                        const token = snapshot.val()
                        return admin.messaging().sendToDevice(token,payload).then(response =>{
                            res.status(200).send('Notification sent')
            console.log("In-valid key : "+key);

            res.status(400).send('Bad request');
    .catch(error => {


ends at this point

this is the function to store your fcm to database

func postToken(token: String, id: String){
    print("FCM Token \(token)")
    let ref = Database.database().reference().child("users").child(id)

here is the function which i used to trigger this API

func sendNotification(id: String, title: String, message: String){
    var url = "your URL"
    var urlComponents = NSURLComponents(string: url)
    urlComponents?.queryItems = [
        URLQueryItem(name: "key", value: self.apiKey),
        URLQueryItem(name: "id", value: id),
        URLQueryItem(name: "title", value: title),
        URLQueryItem(name: "message", value: message)

    Alamofire.request((urlComponents?.url)!).responseJSON { (response) in


the above API was written according to my database structure. you can change it easily for your own structure.

after doing this all you'll be able to send your notifications after hitting the URL

Hope it will give a nice idea to you people to work with your own notifications according to your need.

Original Thread

By anonymous    2018-01-14

I can successfully deploy the HelloWord application fine as per the video guide here.

But now I was following the instructions here in order to link Algolia and Firebase with Cloud Functions, I can run the code on my computer and it updates, but somehow it does not auto-update when I make changes on Firebase.

Secondly, when I deploy the application I get the "deploy complete" message but nothing appears in Firebase>>Functions and Algolia is not updated when I make changes to Firebase.

index.js code

const algoliasearch = require('algoliasearch');
const dotenv = require('dotenv');
const firebase = require('firebase');

// load values from the .env file in this directory into process.env

// configure firebase
  databaseURL: process.env.FIREBASE_DATABASE_URL,
const database = firebase.database();

// configure algolia
const algolia = algoliasearch(
const index = algolia.initIndex(process.env.ALGOLIA_INDEX_NAME);

//synchronize firebase database with algolia index
const contactsRef = database.ref('/contactDetail/botswana');
contactsRef.on('child_added', addOrUpdateIndexRecord);
contactsRef.on('child_changed', addOrUpdateIndexRecord);
contactsRef.on('child_removed', deleteIndexRecord);

function addOrUpdateIndexRecord(contact) {
  // Get Firebase object
  const record = contact.val();
  // Specify Algolia's objectID using the Firebase object key
  record.objectID = contact.key;
  // Add or update object
    .then(() => {
      console.log('Firebase object indexed in Algolia', record.objectID);
    .catch(error => {
      console.error('Error when indexing contact into Algolia', error);

function deleteIndexRecord(contact) {
  // Get Algolia's objectID from the Firebase object key
  const objectID = contact.key;
  // Remove the object from Algolia
    .then(() => {
      console.log('Firebase object deleted from Algolia', objectID);
    .catch(error => {
      console.error('Error when deleting contact from Algolia', error);

package.json code

  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "serve": "firebase serve --only functions",
    "shell": "firebase experimental:functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  "dependencies": {
    "algoliasearch": "^3.24.9",
    "dotenv": "^4.0.0",
    "firebase": "^4.8.1",
    "firebase-admin": "~5.4.2",
    "firebase-functions": "^0.7.1"
  "private": true

Original Thread

By anonymous    2018-02-12

Depends on the scope of your project.

  • If your project is only gonna be for 1 type of mobile client, for example, is only Android. Then set the alarms on the device, and use the Firebase database as data persistence for the user to have a flawless experience between installs and devices.

  • If your project also has to be for web, and send emails along with the notification, then you will have to schedule a cron job. The only question here is how accurate the alarms have to be. This is the important detail because if the alarms need to be exact, you are gonna have to schedule one cronjob each minute, incredibly wasteful, querying the database so often will consume your usage quota pretty fast. Besides, mobile devices have energy saving modes during the meanwhile are not completely active so push notifications can be delayed by the system until the next maintenance window. My recommendation would be to narrow down the alarm to a 30 or 15 minutes window. So you can schedule cronjobs that will query the database for objects in that span of time.

    1. For scheduling a cron job I recommend you the next official video

    2. For sending the push notification using FCM I recommend checking the Functions samples on Github

    3. The best for starting with Functions is this video

    4. And for your database structure, please see example below

  "user_alarms": {
    "uid1": {
      "pushkey1": {
        "full_object": "goes here"
      "pushkey2": {
        "full_object": "goes here"
    "uid2": {
      "pushkey3": {
        "full_object": "goes here"
      "pushkey4": {
        "full_object": "goes here"
  "alarms": {
    "pushkey1": {
      "reduced_object": "mainly_the_time"
    "pushkey4": {
      "reduced_object": "mainly_the_time"

The user_alarms node contains each user alarm, that way the user can see all the alarms that have set. The node alarms is the denormalization for the original node and is the node to be queried on each cron job. It contains a simpler object, only what is needed to perform the query for the upcoming alarms, mainly the trigger time. To improve performance after the FCM push is sent the corresponding object should be deleted.

Original Thread

By anonymous    2018-03-18

I am currently trying to develop some skills with cloud functions and firebase, but i am having a small trouble from the start. I believe there is a easy solution to this, but i have been trying to solve it for a few days now without any success... So, what i am doing - i am following this tutorial's steps / ~ ~ /. At the end, i am deploying the firebase and according to the video, i must see the project console's HTTP and the FUNCTION URL Screenshot from TUTORIAL

Its all fun and roses until i try the exact same steps and i see only the Project Console's http: Screenshot from MY_PROJECT I am pretty sure i am missing some part, but as i replayed the whole video 3 times, i guess it is something that is not said there... Also, i do not see the cloud function in my Firebase project, as shown in the video: Functions in YOUTUBE_TUTORIAL

I do not have anything in my project. What i've tried so far: updating NPM, updating FIREBASE TOOLS, Starting a new project, Overwriting existing project. Nothing. I am assuming i've missed a vital part and i apologize in advance for the (what i think) quite stupid question. I cannot find any solution whatsoever... Thanks for your time!

Original Thread

By anonymous    2018-04-02

I think this will help you.

You don't use functions directly in your app, you upload them to your project. Check the videos for that.

Original Thread

Popular Videos 10757

Submit Your Video

If you have some great dev videos to share, please fill out this form.