In the process of building my application, I used Firebase Cloud Functions that are called by triggers in the Firebase Cloud Firestore. Basically, whenever a record is written to specific collections in my app’s Firestore, the Cloud Functions trigger Slack notifications.

Recently, I built an application for some devs on my team in order to boost sharing of what we learn every week. We are always learning something new, and I wanted a platform that could help orchestrate that. In the process of building my application, I used Firebase Cloud Functions that are called by triggers in the Firebase Cloud Firestore. Basically, whenever a record is written to specific collections in my app’s Firestore, the Cloud Functions trigger Slack notifications. This whole process was a lot of fun, and actually quite powerful. This post is going to cover some basics, and showcase how powerful using cloud functions can be.

Some Background

So before I go into details, here’s some basic info on the app that I built. It’s open source, and you can look at the code on GitHub here.

As I stated in the intro, the whole application is built to orchestrate sharing what the folks I work with learn every week.

  • It scores users based on learning activity that they record each week.
  • The idea is that once a week the winners are recognized, and then there’s an impromptu meeting to highlight some of what was learned.
  • The app includes Slack integration along with Zoom for the meetings.
  • When users record learning activity, a hyperlink is included so that the activities can be reviewed later

Prior to building this application, I had played with Cloud Functions and even built some HTTP endpoints. I was interested in how you could leverage Node Express to literally build out your own API with Firebase Cloud Functions.

However, with this application I wanted to use Cloud Firestore triggers to automatically call these functions when records were saved. By using Cloud Functions with triggers, I was free to build my application and let the Cloud Functions handle the notifications.

The Details

So I’m going to assume that you’ve at least heard of Firebase before. I recommend reviewing the following articles that I’ve written for Angular-In-Depth for sufficient background:

With the basics understood, I’m just going to go into how I setup the triggers and the code involved.

As I stated, I was interested in triggers within my applications database (Cloud Firestore) so that my project’s Slack channel would automatically be updated.

I was specifically looking at triggers for :

  1. When a user was created (registered)
  2. When a user records a learning activity

Since I’m using Slack, I first went about creating a Slack Webhooks. Slack makes this super easy, and I’m not going to walkthrough that because they have great documentation.

Once you’ve got your webhook URL, you just have to create a mechanism to POST to that endpoint.

Within Firebase Cloud Functions, this is super easy because you can just use the request library and the Admin SDK to interact with your Firebase Application and send POST requests. The instructions for the initial setup are on the official Firebase Documentation pages here.

Once you’ve done that, then you use the request and response signature that Firebase’s documentation outlines for triggers. Here’s an example (copied from the Firebase Firestore trigger documentation) :

// this will fire whenever a record is added to the users collection
exports.createUser = functions.firestore
    .document('users/{userId}')
    .onCreate((snap, context) => {
      // Get an object representing the document
      // e.g. {'name': 'Marie', 'age': 66}
      const newValue = snap.data();

      // access a particular field as you would any JS property
      const name = newValue.name;

      // perform desired operations ...
    });

There are a lot of really cool things you can do with triggers, checkout the documentation for more here.

So when it was all said and done, I had the following two functions:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const request = require('request');

// when a new user is registered
exports.createUser = functions.firestore
    .document('users/{userId}')
    .onCreate((snap, context) => {
      const newValue = snap.data();
      const firstName = newValue.firstName;
      const lastName = newValue.lastName;
      const slackWebhook = 'OC_slack1';  
      const message = "user " + firstName + " " + lastName + " just registered!"; 
      
      request.post(
        slackWebhook, 
        { json: { text: message } })
        .then(() => {
            return res.status(200).send('slack message sent successfully');
        })
        .catch(() => { 
            return res.status(500).semd('error occured whens ending slack message'); 
        });
    });

// when a new activity is created
exports.createActivity = functions.firestore
    .document('teamActivity/{Id}')
    .onCreate((snap, context) => {
      const newValue = snap.data();
      const firstName = newValue.firstName;
      const lastName = newValue.lastName;
      const activity = newValue.activity;
      const description = newValue.description;
      const link = newValue.link;
      const points = newValue.points;
      const slackWebhook = 'OC_slack2';  
      const message = firstName + " " + lastName + " just added the activity " + activity
        + " for " + points + " points with the description \"" + description + ".\"  Here's a the link " + link + "."; 

      request.post(
        slackWebhook, 
        { json: { text: message } })
        .then(() => {
            return res.status(200).send('slack message sent successfully');
        })
        .catch(() => { 
            return res.status(500).semd('error occured whens ending slack message'); 
        });
    });

As you can see, when values are written to the users collection and the teamActivity collection, Slack notifications are sent.

One of the coolest parts is that this is just using standard Node Express syntax. So literally if you know how to send requests with Node Express, then you can do the same thing here.

The result is automatic notifications in the project slack channel.

User Registered
Activity Created

Closing Thoughts

This whole process shows how easy it is to get up and running with Firebase Cloud Functions. My understanding is that Firebase Cloud Functions are actually the same thing as Google Cloud Functions, but just specifically made for Firebase. As you can see in the associated documentation, there are a lot of options and the technology is very flexible. I hope my post here has helped you get a basic understanding, checkout the documentation and my application if you have some time.