Introduction to Cloud Functions

Get a brief introduction to Cloud Functions for Firebase.

Cloud Functions for Firebase is a Google Cloud product that lets us automatically run back-end code in response to events triggered either by other Firebase services or by HTTPS requests. With Cloud Functions, we can easily run server-side code without the need to set up a server. Some possible examples of this server-side code include adding roles to users, reacting to changes in a database, or notifying the user when something interesting—such as sending a welcome email when a user signs up—happens. These are events we typically won’t want to run on the client side. Therefore, a perfect use case for Cloud Functions. With the Admin SDK, we can seamlessly interact with other Firebase services from trusted environments via Cloud Functions. For example, we can create a new document in a Cloud Firestore users collection when a user signs up.

How it works

Cloud Functions for Firebase is written in a Node.js environment using either JavaScript or TypeScript. After successfully writing a function, all functions must be deployed to the Cloud Functions runtime before usage. When deploying a function, the Firebase CLI takes all the code associated with that function and puts each function in separate containers and converts a function according to the requirements of Google servers. This allows Google servers to manage the function.

Cloud Functions can either be fired directly with an HTTP request or triggered in response to an event. When this happens, Cloud Functions spins up a server instance for the function in the cloud that activates and runs the function in response to these triggers. Cloud Functions then monitors this function and ensures that the instance created remains active until its promise resolves. As our application usage increases or decreases, Google responds by automatically scaling the server instances needed to run these functions.

Note: Firebase projects must have billing enabled to deploy a Cloud Function. This means all projects must be on the Blaze plan for us to use Cloud Functions. However, Firebase has a generous free tier that allows up to two million function invocations per month. Therefore, simple test applications such as ours probably do not need to worry about exceeding this limit. Check out the Firebase website to learn more.

To enable billing on a project, we perform the following steps:

  1. Head over to the Firebase project dashboard.
  2. Click the “Spark plan” button to show the billing plans.
  3. Click the “Select plan” button under the “Blaze” plan section.
  4. Next, set up a billing budget for the project by entering a value in the provided field. This allows Firebase to alert the project administrators whenever the project costs approach or exceed this amount.

Get hands-on with 1200+ tech skills courses.