DEV Community

Cover image for Firebase cloud functions in Ionic 4 - Complete guide
Sanchit Gupta for Enappd

Posted on • Originally published at enappd.com

Firebase cloud functions in Ionic 4 - Complete guide


This post will take you through the basics of Firebase cloud functions — How to create, deploy and use the cloud functions. Also, we’ll have a look into the cloud function dashboard in Firebase to understand the capabilities.

What is Firebase ?

If you don’t know much about Firebase … you need to catch up with latest tech news. Firebase is the hot stuff in market today to create quick mobile app back-ends, with a ton of built-in and ready-to-integrate features.

The most used feature of Firebase is as a back-end. It does not require any back-end setup or configuration from developer’s end. Along with this back-end, you get a ready-to-use database as well. Some of the other popular features are

  • Push notifications
  • Cloud functions
  • Analytics
  • Ad-mob
  • Crashlytics
  • In-app messages
  • Remote config
  • Social logins
  • …… and more

That being said, I’m sure you are very much interested in learning all of it. You can check out our Firebase social logins with Facebook and Twitter blogs on our site, along with free starters ( 👻 woohoo ! )

What are (Firebase) Cloud Functions?

When you use a ready-to-integrate back-end (BaaS) in your mobile or web-app, you are basically not setting up any back-end on your own. So essentially all the functions / services are written beforehand for you. These functions and services are created based on the most used features by users. e.g.

  • Authentications
  • Database operations — Read, Write, Update, Delete
  • In some cases — Filtering, pagination, geo-queries etc.

But what if you want a custom function or query for your app ? Because you didn’t create the back-end, you cannot write a custom function, right ? Not really 😏. Cloud functions come to your rescue. These are basically simple functions you can write and deploy on the BaaS platform, and these functions will be executed as if they are a part of the platform. (of course, you need to take care of the syntax, requests, responses etc. )

For example, you are a Grocery shopping app. With a BaaS like Firebase, you can Read, Write, Update and Delete the data. But for a certain feature, you need to show the user their monthly expense on the app. Now, Firebase does give you options to query the data by fields like Date etc. But combining data from different tables can be tricky with single or even a complex query. In such a case, you write a function which queries all relevant tables, prepare the data as you want, and sends back to your app in smallest possible data format.

Overall, you can divide the Firebase cloud functions advantages as follows

  1. You can create custom functions to do complex queries e.g. queries combining multiple tables, date and geolocation calculations
  2. Calling a cloud function is as easy as calling a REST API
  3. Complex calculations in the back-end are faster than on front-end e.g. finding matches in a dating app
  4. Cron-jobs can directly run cloud functions on a scheduled basis, doing regular calculations for the database
  5. Creating, updating and deploying Firebase cloud functions is as easy as changing code in your IDE and committing code to Git.
  6. Get rid of managing servers — Firebase takes care of everything
  7. You can test the cloud function on local environment as well

What is Ionic 4?

You probably already know about Ionic, but I’m putting it here just for the sake of beginners. Ionic is a complete open-source SDK for hybrid mobile app development. Ionic provides tools and services for developing hybrid mobile apps using Web technologies like CSS, HTML5, and Sass. Apps can be built with these Web technologies and then distributed through native app stores to be installed on devices.

In other words — If you create native apps in Android, you code in Java. If you create native apps in iOS, you code in Obj-C or Swift. Both of these are powerful, but complex languages. With Cordova (and Ionic) you can write a single piece of code for your app that can run on both iOS and Android (and windows!), that too with the simplicity of HTML, CSS, and JS.

Post Structure

We will go step-by-step to understand the basics of integrating Firebase cloud functions in an Ionic 4 app. We’ll follow these steps

  1. Create a basic Ionic 4 app
  2. Create a Firebase project
  3. Setup Firebase functions and write your first function
  4. Deploy Firebase function and test from your app
  5. Firebase cloud function dashboard and capabilities
  6. Write a complex cloud function and fetch result in the app

Let’s jump right in

1. Create a basic Ionic 4 app

I have covered this topic in detail in this blog.

Creating an Ionic 4 app is as simple as running a single command from command prompt / terminal.

In short, the steps you need to take here are

  • Make sure you have node installed in the system (V10.0.0 at the time of this blog post)
  • Install ionic cli using npm
  • Create an Ionic app using ionic start

You can create a sidemenu starter for the sake of this tutorial. On running ionic start , node modules will be installed. Once the installation is done, run your app on browser using

$ ionic serve

At this moment, your app should look like this


Homepage for Sidemenu starter in Ionic 4

2. Create a Firebase project and connect to your app

Firebase is a Google product (now), so you need to create a “Firebase project” to connect it to your app and keep all related services at one place. You can create a large number of FREE projects in Firebase.

I have covered Ionic 4 Firebase integration in detail in this blog

Please note — Firebase functions can run without attaching Firebase in the app (as REST APIs). You need to copy the Firebase configuration and install angularfire 2 plugin only if you want to attach Firebase database or other functionalities in your app.

Creating Firebase project

Go to console.firebase.google.com and create a new project. Your dashboard will look like this when you have a number of firebase projects


Firebase dashboard with a number of projects

Copy Firebase configuration

Open your project by clicking it, and in the dashboard, select “Add Firebase to your web app”. Follow the procedure and you will get your project’s configuration. Copy the configuration, this will be used to connect your app with Firebase.


Copy Firebase project configuration

Integrate Firebase in your Ionic app

Back in your Ionic app, install Angularfire2 plugin. AngularFire is The official library for Firebase and Angular.

To install the plugin, run the following command from your terminal

$ npm install firebase angularfire2

Paste your Firebase config in environment file of your Ionic app project. The environment file should be in the project root.


Paste your Firebase configuration in environment file

After this, you will need to import angularFire2 and firebase in your app.module.ts and then you can implement CRUD and other functionalities in the app.

3. Setup Firebase functions and write your first function

Firebase functions can be used once we setup firebase-tools in the system. Install it globally with npm using

$ npm install firebase-tools -g

Login to Firebase

Before using Firebase functions, you need to login to your Firebase account using CLI (yeah ! 🤷‍♂). Run

$ firebase login

and it will open the Google login card in your browser. Login to your account and the CLI will receive the authentication info (pretty cool, right ? )


Firebase login in CLI using browser — successful !

Your CLI will look like this


Logging in Firebase using CLI

Connect Firebase to your project

Once you are logged in, you need to define which Firebase project you want to connect to your Ionic 4 app (because you can have more than one in your Firebase console. I have 30+ 😃 ! ). Run

$ firebase init

This will first ask you to choose the project, then choose functions option from the choices. (Don’t worry about other options, I’ll post more blogs on them soon). Follow the instructions and setup all dependencies of Firebase functions


Choose Functions options in Firebase init
Note — Sometimes linting creates errors during deployment. If you face this issue, try re-running firebase init and don’t select linting option when asked

As we discussed earlier , with Firebase Functions, you can essentially write back-end (node.js) functions, test them locally with firebase serve and can then deploy these to your Firebase project, so it can be connected to your app / website.

Once you have Firebase project connected, you will see a functions folder in your project root, as shown below


Firebase functions folder in project root

Create a firebase function to say “Hello World”

Open functions/src/index.ts (or .js, depending on what you chose in previous step). This is the file that will contain functions to be executed by Firebase. Firebase creates a URL for each of these functions when deployed, so you can call these functions like a REST API


Default index.ts in Firebase functions folder

By default, Firebase gives you a helloWorld function, uncomment it and you can use it as is. Let’s understand what is happening here (if you haven’t used node.js ever)

  • export exports the function as a individual entity. You can have as many functions as you want in this file itself
  • request is the request you send from front-end, similar to a REST API. It is relevant for POST requests
  • response is the response Firebase cloud function will send back to your app

In this sample case, the function is simple sending back a “hello from Firebase” (irrespective of request i.e. this is a GET type request). Change the response as you like !

Congratulations, you just wrote your first Firebase cloud function.

⭐️️⭐️️️ Extra : Adding CORS to Firebase function to run locally⭐️️⭐️️️

When developing an Ionic 4 app, you’ll do most of your development in browser. So it makes sense to get the Firebase function response in serve as well. By default, Firebase does not allow response to localhost urls. To avoid this, we will have to add CORS middleware in the Firebase function. If you want to test simply in your phone, CORS middleware is not required.

Don’t worry, it is very simple.

  1. Add CORS dependency in your functions/package.json

Add CORS in dependency

2. Move in functions folder, and run npm install again to install the new dependency

3. Import CORS in Firebase functions file, and modify the response code as follows

Add CORS in Firebase function response

Now, you can run the Firebase function in your ionic serve as well !

4. Deploy Firebase function and test from your app

Now that the function is ready, we will deploy it to Firebase. This way we can use it in the app directly (similar to a REST API)

Deploy Firebase function

To deploy the firebase function, in your root folder itself, run

$ firebase deploy --only functions

This will make sure you are only deploying functions to Firebase. This is especially useful when you have multiple things attached to Firebase, and you have made changes in only one of them.

Deployment will look like this in the CLI


Firebase functions deployment

Notice in the function URL, it provides you the URL to call the cloud function. https://us-central1-full-firebase-ionic4.cloudfunctions.net/helloWorld

Run Firebase function in local environment

If you don’t want to deploy everytime you make a change in your Firebase function, you can serve the functions locally and use the local function URL for testing.

Run

$ firebase serve

This will serve the functions locally, and provide you a local URL of each of the function. Replace the function web URL with local URL and you’ll be able to access the function in your app.

Calling the cloud functions from Ionic 4 app

I modified the app to have a button with which we can call the cloud function. Right below the button, we will receive the response from Firebase cloud function.


Modify the homepage to call Firebase function with a simple button

To enable our app to make HTTP requests, we import HttpClient in our app.module.ts


Import HttpCient in app.module.ts

and in our home.page.ts page

import { HttpClient } from "@angular/common/http";
...
constructor(private http: HttpClient){}

Now, on the click of our button, we’ll call the cloud function, and receive the response. The home.page.ts looks like following

Just for reference, the home.page.html looks like following

Now, hit the button, and you’ll receive a response from Firebase function !


Firebase function works !!

🎊 Voila ! Your first Firebase cloud function is working like a charm !


Oh yeah !

Little troubleshooting tip

If you face pre-deploy linting error during deployment, go to your firebase.json file and remove the pre-deploy script calls from JSON.


Remove the pre-deploy scripts if you face pre-deploy errors

5. Firebase cloud function dashboard

Till now, we were doing everything in the CLI or front-end code. It becomes challenging to maintain a large number of cloud functions, and their executions or errors with CLI alone. Firebase has provided a very good solution for this.

In Firebase console, you can actually check all the functions deployed, their executions and if they faced any errors.

List of deployed functions


List of functions deployed in Firebase

You can see the functions deployed in the Functions tab of Firebase console.

Execution log

You can also check the execution of each / all function(s) in Firebase console — Logs tab


Check firebase function logs

The logs show general comments of errors returned by the function. This is especially useful if you want to track any error happening in your functions.

Functions’ health

If you have a large number of functions, and huge amount of executions, then a list of logs won’t suffice. You can check an overview of errors in the Health tab


Firebase console showing health of function execution

Usage log

To track how many functions you execute in a time period (to check against your billing plan) you can use the Usage tab


Firebase function usage log

This way, Firebase provides a good number of visual and logging tools to make your life easy when dealing with cloud functions.

6. Write a cloud function with complex query

For the first example, we simply responded with a “Hello from Firebase”. But that is not sufficient for most of the apps. Apps often need to query the database in various ways and need the final result as a response.

I am putting out a similar example here. The example is implemented with FireStore DB. This is a sample example for finding a driver in a Taxi Booking Platform. The logic isn’t as complex as that of Uber etc. but queries a couple of DB tables, and then updates certain documents in the DB as well, before sending a response to the app. Let’s have a look.

Let us understand what is happening here

  • As we did before, we imported certain dependencies. Additionally, firebase-admin is also imported, which is required to allow Firebase function to access your Firebase project’s DB (yes, there is no direct connection 😺)
  • Same as before, we implemented CORS for localhost usage
  • Since there is a request object coming in, this is a POST request.
  • In the first step, the req.body is read, and stored in a variable
  • Then, drivers collection is read in the DB, and a driver matching the email driver@enappd.com is filtered. In a production app, this will be the place where the app’s “driver finding logic” will go.
  • Once the driver is found, the customer’s record is updated with origin and destination storing customer’s coordinates.
  • Once the customer is updated, the driver record is also updated, marking him unavailable, and saving user_id in driver’s record
  • Once all this process is done, the response is sent to the app. The response contains the information of the driver selected. This information will be used in the app to show the customer which driver is arriving for the ride.

This was a simple example of how Firebase cloud function can perform complex queries in your DB, and return the result to your app quickly. If all this was done on front-end, the response time would be much larger because of the multiple DB query hits.

Conclusion

In this post, we learned how to create, integrate, deploy and test simple Firebase functions. We also saw the Firebase console capabilities related to functions. We had a look at how complex queries can be performed with Firebase functions, citing an example from a Taxi Booking Platform. Firebase functions are an amazing tool to enable your app do much more than simple DB querying, or making complex queries from front-end.

Stay tuned for more Ionic blogs!

Next Steps

Now that you have learned the implementation of Firebase functions in Ionic 4, you can also try

If you need a base to start your next Ionic 4 app, you can make your next awesome app using Ionic 4 Full App


Use Ionic 4 Full app for your next awesome app

References

Top comments (0)