Why roam around when you were meant to stay high?
Ever faced a situation where your application needs to run a piece of code in response to any HTTPS request or a change in your Firestore? More so ever, your application runs on different devices and needs a central brain power?! Cloud Functions for Firebase are here to rescue and the best part is that you don’t need to manage and scale your own servers for it!
So What are Firebase Cloud Functions?
Cloud functions are powerful methods that give your apps a secure and strong single point of change without the hassle of publishing or deploying your entire application again. You have the choice to write your cloud functions in JavaScript or TypeScript.
You can imagine them to be like efficient computing machines that will run your logic whenever they are triggered. A trigger is like the play button to start your function in action. It can be anything interesting in the Firebase database, like adding or modifying a document, or it could be an HTTPs request (GET/POST). For example, execute a function to generate a thumbnail whenever an image is uploaded in your collection.
So, Cloud Firestore, gives you generic HTTP onRequest() event, which supports routers and apps managed by the Express web framework and four triggers to handle the firestore events:
- OnCreate (new document added)
- OnUpdate (existing document modified)
- OnDelete (existing document removed)
- OnWrite (any of the create, update or delete action performed)
What does Firebase Cloud Function do?
Firebase Cloud Function simply runs your back-end logic with automatic scaling and without the hassle of server management. Your code is secure and you have zero maintenance issues. Once you deploy your function, it is invoked when the event matches the trigger of the function and Google takes care of load being increased or decreased and cleaning up the instances. It only charges for the specific event usage.
Useful scenarios for your application can be diverse, but typical cases where flying in the clouds would be helpful as shared in official docs are:
- Notify users when something interesting happens.
- Perform database sanitization and maintenance.
- Execute intensive tasks in the cloud instead of in your app.
- Integrate with third-party services and APIs.
Implementing A Firebase Cloud Function
To implement your own cloud function, you’ll just need four simple ingredients to get started. We will look into an Angular project to demonstrate the process of writing, testing and deploying your cloud function.
Getting the Ingredients:
- Node.js (Install Node in your machine)
- firebase-cli :
npm install -g firebase-tools
(Install this package) - VS Code (or your editor of choice!)
- Firebase project (If you don’t have an existing project, firebase console offers a friendly and easy way to setup your project)
Recipe for Cloud Functions:
-
Create Angular Project & Bind it with Cloud Firestore:
Simply create a new Angular project by running following command in your choice of directory: , or bind your existing project with Firebase by running the following commands in the given order:
-
firebase login
(login with your firebase credentials) firebase init firestore
(to initialize firestore)firebase init functions
(to initialize cloud functions)-
npm install
If the commands were successful, your project structure should look like this:
Reference: Firebase Google Docs
If your project is already using firebase power, make sure to validate functions are initialized by checking the firebase.json file in your project.
-
Import Modules & App Initialization:
If you plan to use the firebase triggers, add these lines to load the modules and app initialization:
// The Cloud Functions for Firebase SDK to create Cloud Functions and set up triggers.
const functions = require('firebase-functions');
// The Firebase Admin SDK to access Firestore.
const admin = require('firebase-admin');
admin.initializeApp();
-
Shoot your First Function
Code the cloud function that solves your problem. But analyze the suitable trigger for your requirement.
-
Example: Hello Cloud Functions
We’ll try out the simple HTTPS GET trigger for our legacy hello world function. In your src
folder, make a folder for hello-world and make an index.ts
file in it with the following code:
const functions = require('firebase-functions');
export const helloWorldFunc =
functions.https.onRequest((req, res) => {
res.send("Hello Cloud Functions")
});
The function is simply making the necessary import and listening to HTTPS requests and always sending the greeting string in return. If you want to respond based on a specific URL path, you can add necessary conditions for your code.
This hierarchy is not necessary will help you in managing multiple functions for your same project:
In your main index.ts file, export the function by the following:
export const helloWorld = helloWorldFunc;
-
Debug Cloud Functions Locally
Build the function using tsc and attach the debugger using the command:
firebase emulators:start --inspect-functions
Attach breakpoints and debug your code.
Note: if your function is triggered on one of the firestore events, make sure you are manipulating your collections on http://localhost:4000/firestore/ to debug your code.
-
Deploy & Test Cloud Functions
When you are happy with your cloud function and want to test it in action, simply deploy it. You can deploy the function in one of the three options:
- deploy all using the following command:
firebase deploy --only functions
- deploy a specific function:
firebase deploy --only functions:hello_world
- deploy multiple functions using comma separated keyword:
firebase deploy --only
functions:function_1,functions:function_2,functions:functio n_3
If you are re-deploying an existing function, it’s a good practice to first remove it from the functions list and then deploy, to make sure the latest instance is running. Your deployed function should appear in the dashboard list:
For tracking purposes and debugging, you can check logs at
https://console.cloud.google.com/functions
Who uses Firebase Cloud Function?
Firebase is much popular in the tech world and according to stackshare, it is used by 2854 companies including Alibaba, The New York Times and many more. Companies that use cloud functions include Jounce, Bunch, TechStack and many more.
So, Will You Try it Out?
Hope you enjoyed paragliding in the cloud functions! This practical guide by Codelabs will be helpful to execute your first project and the official docs are always the best reference point to solve your queries!
Moreover, if you are interested in checking out some cool and efficient code for popular use cases of Cloud Functions for Firebase, check it on this Firebase GitHub repository. If you have any queries or want to discuss a problem case, feel free to reach out at [email protected]