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

Prerequisites:

1. Firebase project.

2. Very basic knowledge of Node.js

3. 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 https://nodejs.org/en/ 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 logout

Creating 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 functionsyou 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.

import * as admin from 'firebase-admin';

Then we have to add the Firebase Admin SDK to access the Firebase Realtime Database.

admin.initializeApp(functions.config().firebase);

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:

export const myFirstCloudFun= functions.database.ref('/users/{userId}').onWrite(async (event, context) =>{

 

})

The next step is getting the user’s name and token so we can create the notification payload as below:

export const myFirstCloudFun= functions.database.ref('/users/{userId}').onWrite(async (event, context) =>{

const user= event.after.val()

const name = user.name

const token = user.token

 

})

 

Next step is to create our payload so we can send the notification

export const myFirstCloudFun= functions.database.ref('/users/{userId}').onWrite(async (event, context) =>{

const user= event.after.val()

const name = user.name

const token = user.token

const payload = {

           notification: {

             title: 'Hi '+ name,

             body: 'Welcome to our first cloud function App' ,

             sound : "default"

           }

         };

})

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.

export const myFirstCloudFun= functions.database.ref('/users/{userId}').onWrite(async (event, context) =>{
const user= event.after.val()
const name = user.name
const token = user.token
const payload = {
           notification: {
             title: 'Hi '+ name,
             body: 'Welcome to our first cloud function App' ,
             sound : "default"
           }
         };
return admin.messaging().sendToDevice(token, payload)
         .then(function(response){
             console.log("Successfully message is sent:", response);
         console.log(response.results[0].error);})
         .catch(function(error) {
           console.log("Error while sending message:", error);
       }
   )

})

Deploy the Cloud Function:

To Deploy our function we will again use the Firebase CLI

firebase deploy

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:

{ "functions": { "predeploy": [ "npm --prefix ./functions/ run lint", "npm --prefix ./functions/ run build" ] } }

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:

Log.d("FCMToken", "token "+ FirebaseInstanceId.getInstance().getToken());

and on iOS:

InstanceID.instanceID().token()

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: https://firebase.google.com/docs/reference/rest/database

 after writing the user object to the firebase database, our database should look something like this:

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

References:

  1. https://medium.com/@carlosazaustre/how-to-create-your-first-cloud-function-for-firebase-17711831a67c
  2. https://www.techotopia.com/index.php/Installing_the_Firebase_CLI
  3. https://firebase.google.com/docs/functions
  4. https://firebase.google.com/docs/functions/use-cases
  5. https://firebase.google.com/docs/functions/database-events
  6. https://firebase.google.com/docs/functions/firestore-events
  7. https://wsvincent.com/install-node-js-npm-windows/
  8. https://firebase.google.com/docs/cloud-messaging/concept-options
featured_image
About the Author

Randa Fahmy

Senior Software Engineer @ Andela

Thanks for subscribing!

 

More Insights

July 19, 2019

How To Create Your First Firebase Cloud Function Project

Randa Fahmy

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

Prerequisites:

1. Firebase project.

2. Very basic knowledge of Node.js

3. 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 https://nodejs.org/en/ 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 logout

Creating 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 functionsyou 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.

import * as admin from 'firebase-admin';

Then we have to add the Firebase Admin SDK to access the Firebase Realtime Database.

admin.initializeApp(functions.config().firebase);

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:

export const myFirstCloudFun= functions.database.ref('/users/{userId}').onWrite(async (event, context) =>{

 

})

The next step is getting the user’s name and token so we can create the notification payload as below:

export const myFirstCloudFun= functions.database.ref('/users/{userId}').onWrite(async (event, context) =>{

const user= event.after.val()

const name = user.name

const token = user.token

 

})

 

Next step is to create our payload so we can send the notification

export const myFirstCloudFun= functions.database.ref('/users/{userId}').onWrite(async (event, context) =>{

const user= event.after.val()

const name = user.name

const token = user.token

const payload = {

           notification: {

             title: 'Hi '+ name,

             body: 'Welcome to our first cloud function App' ,

             sound : "default"

           }

         };

})

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.

export const myFirstCloudFun= functions.database.ref('/users/{userId}').onWrite(async (event, context) =>{
const user= event.after.val()
const name = user.name
const token = user.token
const payload = {
           notification: {
             title: 'Hi '+ name,
             body: 'Welcome to our first cloud function App' ,
             sound : "default"
           }
         };
return admin.messaging().sendToDevice(token, payload)
         .then(function(response){
             console.log("Successfully message is sent:", response);
         console.log(response.results[0].error);})
         .catch(function(error) {
           console.log("Error while sending message:", error);
       }
   )

})

Deploy the Cloud Function:

To Deploy our function we will again use the Firebase CLI

firebase deploy

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:

{ "functions": { "predeploy": [ "npm --prefix ./functions/ run lint", "npm --prefix ./functions/ run build" ] } }

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:

Log.d("FCMToken", "token "+ FirebaseInstanceId.getInstance().getToken());

and on iOS:

InstanceID.instanceID().token()

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: https://firebase.google.com/docs/reference/rest/database

 after writing the user object to the firebase database, our database should look something like this:

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

References:

  1. https://medium.com/@carlosazaustre/how-to-create-your-first-cloud-function-for-firebase-17711831a67c
  2. https://www.techotopia.com/index.php/Installing_the_Firebase_CLI
  3. https://firebase.google.com/docs/functions
  4. https://firebase.google.com/docs/functions/use-cases
  5. https://firebase.google.com/docs/functions/database-events
  6. https://firebase.google.com/docs/functions/firestore-events
  7. https://wsvincent.com/install-node-js-npm-windows/
  8. https://firebase.google.com/docs/cloud-messaging/concept-options
featured_image
About the Author

Randa Fahmy

Senior Software Engineer @ Andela

Thanks for subscribing!

 

More Insights

Evolving HR Through Design Thinking

Growing up as a child, a lot of things intrigued me. Top on the list was food, my special stones (ak...

23_August_2019

Finding Answers: Benedicte Musabimana’s Dev Journey

"When I was a kid, I always wanted to know how a computer or a mobile phone worked." Benedicte is...

21_August_2019

Introducing The Andela Talent Marketplace

Andela set out as a company to advance human potential by investing heavily in building technology l...

20_August_2019

On Designing Good Microservices Architectures

It may be difficult to know exactly what constitutes a well-designed microservice on your first assi...

19_August_2019

RubyConf Kenya 2019: My Nairuby Recap

Two weeks ago was the first time I attended a Ruby conference outside my home country, and boy was i...

14_August_2019

How To Manage Communication as a Distributed Product Manager

With more companies embracing distributed and remote work teams, the communication challenge tak...

9_August_2019

Partners

Tap into a global talent pool and hire the “right” developers in days, not months.

Developers

Accelerate your career by working with high-performing engineering teams around the world.

BECOME A DEVELOPER

Hire Developers

We take great pride in matching our developers with the best partners. Tell us about your team below!

preloader_image

Thank you for your interest

A member of our team will reach out to you soon.