Understanding Firebase Cloud Functions and Triggers 🔥☁️ ⚡

Understanding Firebase Cloud Functions and Triggers 🔥☁️ ⚡

For Firebase developers, Cloud Functions for Firebase provides a way to extend the behaviour of Firebase and integrate Firebase features through the addition of server-side code. This can also be referred to as Backend as a Service

This extends the use of Firebase from just serving as a data store for your application by powering it with the ability to perform logic which would require a server-side environment. This article provides code snippets which can be used to execute functions on the occurrence of events.

In addition, we'll talk about a recently introduced feature, Scheduling Cloud Functions for Firebase (cron) . This allows developers to schedule a function for regular execution, similar to a cron job.

Firebase Cloud Functions

Firebase Cloud Functions for Firebase let you automatically run backend code in response to events triggered by Firebase features and HTTPS requests. Your code is stored in Google's cloud and runs in a managed environment. There's no need to manage and scale your own servers.

Google Cloud Functions is Google's serverless compute solution for creating event-driven applications. It is a joint product between the Google Cloud Platform team and the Firebase team.

You should use Cloud Functions for Firebase if you're a developer building a mobile app or mobile web app. Firebase gives mobile developers access to a complete range of fully managed mobile-centric services including analytics, authentication and Realtime Database. Cloud Functions rounds out the offering by providing a way to extend and connect the behaviour of Firebase features through the addition of server-side code. For developers that need a more full-featured backend, Cloud Functions provides a gateway to the powerful capabilities in Google Cloud Platform.

Functions can be written in JavaScript or TypeScript.

Firebase Cloud Functions Triggers and Code Snippets

To get started with Cloud Functions on Firebase, you can follow the instructions here to set up. If you would also like to test Cloud Functions locally, install the emulator using the guide here

Cloud Firestore triggers

The Cloud Functions for Firebase SDK exports a functions.firestore object that allows you to create handlers tied to specific Cloud Firestore events such as:

  • onCreate : triggered when a document is written to for the first time.
  • onUpdate : triggered when a document already exists and has any value changed.
  • onDelete : triggered when a document with data is deleted.
  • onWrite : triggered when onCreate, onUpdate or onDelete is triggered.
// Listens for any document created in the users collection
exports.createUser = functions.firestore
    .document('users/{userId}')
    .onCreate((snap, context) => {
      // Get an object representing the document
      const newValue = snap.data();
      const name = newValue.name;
      // perform desired operations ...
    });

Check out more code snippets here

Realtime Database triggers

Functions let you handle database events at two levels of specificity; you can listen for specifically for only creation, update, or deletion events, or you can listen for any change of any kind to a path. Cloud Functions supports these event handlers for Realtime Database:

  • onWrite() : triggered when data is created, updated, or deleted in the Realtime Database.
  • onCreate() : which triggered when new data is created in the Realtime Database.
  • onUpdate() :which triggered when data is updated in the Realtime Database.
  • onDelete() : which triggered when data is deleted from the Realtime Database.
// Listens for new messages added to /messages/:pushId/original and creates an
// uppercase version of the message to /messages/:pushId/uppercase
exports.makeUppercase = functions.database.ref('/messages/{pushId}/original')
    .onCreate((snapshot, context) => {
      // Grab the current value of what was written to the Realtime Database.
      const original = snapshot.val();
      console.log('Uppercasing', context.params.pushId, original);
      const uppercase = original.toUpperCase();
      // You must return a Promise when performing asynchronous tasks inside a Functions such as
      // writing to the Firebase Realtime Database.
      // Setting an "uppercase" sibling in the Realtime Database returns a Promise.
      return snapshot.ref.parent.child('uppercase').set(uppercase);
    });

Check out more code snippets here

Firebase Authentication triggers

You can trigger Cloud Functions in response to the creation and deletion of Firebase user accounts.

// Trigger a function on user creation
exports.sendWelcomeEmail = functions.auth.user().onCreate((user) => {
  // Send the email...
});

Check out more code snippets here

Google Analytics for Firebase triggers

Google Analytics for Firebase provides event reports that help you understand how users interact with your app. With Cloud Functions, you can access conversion events you have logged and trigger functions based on those events.

// triggered whenever user activity generates a conversion event.
exports.sendCouponOnPurchase = functions.analytics.event('in_app_purchase').onLog((event) => {
  // ...
});

Check out more code snippets here

Firebase Crashlytics triggers

You can trigger a function in response to Crashlytics issue events including new issues, regressed issues, and velocity alerts.

Crashlytics triggers handle events such as:

  • onNew : when your app experiences an issue for the first time.
  • onRegressed() : when an issue reoccurs after it's closed in Crashlytics
  • onVelocityAlert() : when a statistically significant number of sessions in a given build crash
exports.sendOnNewIssue = functions.crashlytics.issue().onNew(async (issue) => {
  // do something...
});

Check out more code snippets here

Cloud Storage triggers

You can trigger a function in response to the uploading, updating, or deleting of files and folders in Cloud Storage.

  • functions.storage.object() : to listen for object changes on the default storage bucket.
  • functions.storage.bucket('bucketName').object() : to listen for object changes on a specific bucket.
exports.generateThumbnail = functions.storage.object().onFinalize(async (object) => {
  // generateThumbnail code...
});

Check out more code snippets here

Remote Config triggers

You can trigger a function in response to Firebase Remote Config events, including the publication of a new config version or the rollback to an older version.

Check out more code snippets here

Cloud Pub/Sub triggers

Google Cloud Pub/Sub is a globally distributed message bus that automatically scales as you need it. You can create a function that handles Google Cloud Pub/Sub events by using functions.pubsub.

// trigger a pub/sub function
exports.helloPubSub = functions.pubsub.topic('topic-name').onPublish((message) => {
  // ...
});

Check out more code snippets here

Scheduling Firebase Cloud Functions

Firebase also supports a new type of Pub/Sub function, built on top of Cloud Scheduler, that automatically configures Cloud Scheduler, along with a Pub/Sub topic, that invokes a function that you define using the Cloud Functions for Firebase SDK.

export scheduledFunctionCrontab =
functions.pubsub.schedule('every 3 hours').onRun((context) => {
    console.log('This will be run every 3 hours daily')
})

Besides the normal costs for Cloud Functions, the costs for this feature are the same as if you set up the underlying infrastructure manually - for more information, check out the full pricing information for Cloud Scheduler and Cloud PubSub.

Cloud Functions Cost

Cloud Functions are priced according to how long your function runs, how many times it's invoked and how many resources you provision for the function. If your function makes an outbound network request, there are also additional data transfer fees.

Cloud Functions includes a perpetual free tier to allow you to experiment with the platform at no charge. Note that even for free-tier usage, Google Cloud requires a valid billing account. You can read more about the pricing here

Addtional Resources

Thanks for reading through! Let me know if I missed any step, if something didn’t work out quite right for you or if this guide was helpful.

You can also read about how I used Google Cloud Function and Cloud Scheduler to build a Slack Reminder App here