How To Create Your First Firebase Cloud Function Project

This is a tutorial on how you can create your first Firebase Cloud Function project.


1. Firebase project.2. Very basic knowledge of Node.js3. Knowledge of NoSQL database

What is Firebase Cloud Function?

Cloud Functions for Firebase lets 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, for example, if we have a chatting mobile app that uses firebase to store the messages and we want to filter the messages before they are written to the database so as to make sure there are no bad words included in any message, before the cloud functions were made that was really hard to achieve and most probably we would need someone to write a backend code to do this check, but today, all we need to do is just write a simple cloud function that triggers whenever any message is added to our database and filter it out.It is very powerful especially for mobile developers that have no knowledge on how to write web apps or backend, you can also integrate with third-party APIs like Slack and Github, but in this tutorial we will go through “Realtime Database triggers”, realtime database triggers are functions triggered when a database event happens, in this tutorial we will go through the onWrite(), which triggers a cloud function when data is added, updated or deleted from a specific node in the realtime database.To get started with our cloud function we first have to install the Firebase CLI.

Installing the Firebase CLI:

The Firebase CLI is the method by which Firebase Cloud Functions are deployed and managed from the command-line of a terminal or command prompt window, the Firebase CLI is built on Node.js, therefore, the first step in installing the CLI is to set up the Node.js, we will now walk through the steps on how to install the CLI starting from installing node and npm.1. Go to and click on the Installer that says “Recommended For Most Users”.2. Launch the .msi downloaded file and go through the install process but make sure to select the npm package manager on the Custom Setup screen, not the default of Node.js runtime. This way we’ll install Node and NPM at the same time, To confirm we’ve installed everything correctly, open the “Command Prompt”, To confirm Node is installed type node -v which will print the current version number. To confirm NPM is installed, type npm -v, which will print its current version number.3. Install the Firebase Tools package, note that the Firebase CLI is installed as a part of the Firebase Tools package, install it using the following npm command within a terminal or command-prompt window: npm install -g firebase-tools, note that on some platforms such as macOS and Linux it may be necessary to execute the above command with superuser privileges: sudo npm install -g firebase-tools.Now we can create a local cloud functions project but before we create the project we have to sign in to Firebase with the same account we use in our firebase project, to sign, type the following command: firebase login the command will prompt for permission to gather anonymous usage data before displaying a browser window within which to select the Google account associated with your Firebase development projects, go back to the CMD after you log in using the browser you will find a message stating that you have successfully logged in.To logout at any point in the future, simply execute the following Firebase CLI command: firebase logoutCreating your first Firebase Cloud Function Project:1. To create our firebase cloud function project locally we first have to navigate to the location that you want to keep your cloud functions projects then create a folder and name it with whatever you want to name it but I suggest that you name it with your project’s name.2. We will use the Firebase CLI to create our project, on the CMD/Terminal, change the directory to the new project folder and run the following command to create the project: firebase init functions,you will find a message telling you “You're about to initialize a Firebase project in this directory:”, “ Are you ready to proceed? (Y/n)”, then type “y”3. The Firebase CLI will tell you the following message:“First, let's associate this project directory with a Firebase project. You can create multiple project aliases by running firebase use --add, but for now, we'll just set up a default project. Select a default Firebase project for this directory: (Use arrow keys)” then choose the project you want to apply the cloud functions on.4. After you choose the desired project, it will ask you which language you want to use to write cloud functions, in this tutorial I will be using Typescript, then it will ask you if you want to install dependencies with NPM, choose “y”.5. You are all set and ready to write your first cloud function now!Writing your first Cloud Function:In this tutorial, we will write a cloud function that will trigger whenever any User is added/updated and sends him a notification that greets him including his name.Suppose we have a node called users and each node has name and token fields.Note: the token is the value of the device token that is known as the registration token that is a unique token string that identifies each client app instance. The registration token is required for single device and device group messaging. Note that registration tokens must be kept secret.Use any editor to write your code, I usually use Visual Studio Code.Open the folder that you created for your cloud function project, you will find a folder named “functions”, open it then open the “src” folder then open index.js.From here you could start writing your functions, when you open the index.js file you will find an import and a commented function.First, we have to import firebase-admin as we will use it to send the notifications and access the database.[pastacode lang="javascript" manual="import%20*%20as%20admin%20from%20'firebase-admin'%3B" message="" highlight="" provider="manual"/]Then we have to add the Firebase Admin SDK to access the Firebase Realtime Database.[pastacode lang="javascript" manual="admin.initializeApp(functions.config().firebase)%3B" message="" highlight="" provider="manual"/]After we initialize the app, we need to write our cloud function as the below syntax, we need to reference the users node and navigate to each user that is created or updated as below:[pastacode lang="javascript" manual="export%20const%20myFirstCloudFun%3D%20functions.database.ref('%2Fusers%2F%7BuserId%7D').onWrite(async%20(event%2C%20context)%20%3D%3E%7B%0A%0A%C2%A0%0A%0A%7D)%0A" message="" highlight="" provider="manual"/]The next step is getting the user’s name and token so we can create the notification payload as below:[pastacode lang="javascript" manual="export%20const%20myFirstCloudFun%3D%20functions.database.ref('%2Fusers%2F%7BuserId%7D').onWrite(async%20(event%2C%20context)%20%3D%3E%7B%0A%0Aconst%20user%3D%20event.after.val()" message="" highlight="" provider="manual"/]Next step is to create our payload so we can send the notification[pastacode lang="javascript" manual="export%20const%20myFirstCloudFun%3D%20functions.database.ref('%2Fusers%2F%7BuserId%7D').onWrite(async%20(event%2C%20context)%20%3D%3E%7B%0A%0Aconst%20user%3D%20event.after.val()'Hi%20'%2B%20name%2C%0A%0A%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0body%3A%20'Welcome%20to%20our%20first%20cloud%20function%20App'%20%2C%0A%0A%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0sound%20%3A%20%22default%22%0A%0A%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%7D%0A%0A%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%C2%A0%7D%3B%0A%0A%7D)%0A%0A" message="" highlight="" provider="manual"/]Finally we will write the code that sends our notification as below then save your code:Note: It is important to log the errors or the successful response so you can track your results, you can always find your logs in the firebase console under the cloud functions tab from the side menu.[pastacode lang="javascript" manual="export%20const%20myFirstCloudFun%3D%20functions.database.ref('%2Fusers%2F%7BuserId%7D').onWrite(async%20(event%2C%20context)%20%3D%3E%7B%0Aconst%20user%3D%20event.after.val()'Hi%20'%2B%20name%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20body%3A%20'Welcome%20to%20our%20first%20cloud%20function%20App'%20%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20sound%20%3A%20%22default%22%0A%20%20%20%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20%20%7D%3B%0Areturn%20admin.messaging().sendToDevice(token%2C%20payload)%0A%20%20%20%20%20%20%20%20%20.then(function(response)%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20console.log(%22Successfully%20message%20is%20sent%3A%22%2C%20response)%3B%0A%20%20%20%20%20%20%20%20%20console.log(response.results%5B0%5D.error)%3B%7D)%0A%20%20%20%20%20%20%20%20%20.catch(function(error)%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20console.log(%22Error%20while%20sending%20message%3A%22%2C%20error)%3B%0A%20%20%20%20%20%20%20%7D%0A%20%20%20)%0A%0A%7D)%0A" message="" highlight="" provider="manual"/]Deploy the Cloud Function:To Deploy our function we will again use the Firebase CLI[pastacode lang="javascript" manual="firebase%20deploy" message="" highlight="" provider="manual"/]Then you are all set! Note that if you face an issue while deploying with the firebase.json, just replace the script inside with the following:[pastacode lang="javascript" manual="%7B%20%22functions%22%3A%20%7B%20%22predeploy%22%3A%20%5B%20%22npm%20--prefix%20.%2Ffunctions%2F%20run%20lint%22%2C%20%22npm%20--prefix%20.%2Ffunctions%2F%20run%20build%22%20%5D%20%7D%20%7D" message="" highlight="" provider="manual"/]Test The Cloud Function:After our function is deployed successfully, now we need to do is test our function and make sure that it works as expected.In this example we need to have two attributes for each user object which are the name and the token, to get the device token on Android:[pastacode lang="javascript" manual="Log.d(%22FCMToken%22%2C%20%22token%20%22%2B%20FirebaseInstanceId.getInstance().getToken())%3B" message="" highlight="" provider="manual"/]and on iOS:[pastacode lang="javascript" manual="InstanceID.instanceID().token()" message="" highlight="" provider="manual"/]Now, after we get the name and the token of the user, we need to create an object of these two attributes and write them to the firebase database, to do that we could use either the Firebase SDK or Firebase database REST API, you can find the link below on how to use firebase database REST API: writing the user object to the firebase database, our database should look something like this:

users randa

Once we write our object to the database, our cloud function should be triggered and send the notification successfully, and here we go!References:


Related posts

The latest articles from Andela.

Visit our blog

Overcoming the Challenges of Working With a Mobile FinTech API

Andela community member Zzwia Raymond explores why, despite the potential of the MTN Mobile Money platform and its API, there are technical hurdles, from complex documentation to enhancing functionality.

How Andela Transformed Tech Hiring in 10 Years

Celebrating 10 years of transforming tech hiring by unlocking global talent across Africa, Latin America and beyond, Andela has surpassed its original goal by training nearly 110,000 technologists and assembling one of the world's largest remote tech talent marketplaces.

What GPT-4o and Gemini releases mean for AI

The latest generative AI models from OpenAI (GPT-4) and Google (Gemini 1.5 Pro, Veo, etc.) promise improved capabilities, lower costs, and transformative applications across various industries by integrating advanced AI technologies into business operations.

We have a 96%+
talent match success rate.

The Andela Talent Operating Platform provides transparency to talent profiles and assessment before hiring. AI-driven algorithms match the right talent for the job.