Skip to content

Calling Cloud Functions v2 From Your App

Cloud Functions for Firebase is a tool that lets you run code automatically on a server without managing it, when certain things happen in Firebase or when someone sends a request through the web.

In this tutorial we’ll be talking about Cloud Functions v2.

There are 2 types of functions:

  • HTTP functions: A normal function that can be run by calling an HTTP endpoint.
  • HTTP callable functions: Similar to an HTTP function but handles authentication for you. This is really useful if you’re already using Firebase Authorization in your project. To use it, you’re required the use the Firebase Functions SDK on Android.

Setup Cloud Functions in Firebase:

To learn how to setup the project you can follow the tutorial in Firebase’s website.

Write Cloud Functions:

Now that you have your project working let’s write a simple function that accepts a name and returns a greeting.

import * as functions from "firebase-functions/v2/https";

export const hello = functions.onCall(async (request) => {
    const name =
    return {
        "response": `Hi ${name}`

To deploy the function use:

firebase deploy --only functions

Make sure your function is deployed correctly before proceeding to the next step.

Call Cloud Functions from Your App:

Now that you have your function, let’s call it from your app. Remember that HTTP callable functions require you to be authenticated so first make sure you somehow authenticate with Firebase Authentication.

Start by including the dependency

implementation platform('')
implementation ''

Now let’s call the function

	mapOf("name" to "Victor)
).addOnSuccessListener {
	// handle success
}.addOnFailureListener { exception ->
 	// handle error

If you’re using Coroutines in your project you can wrap the call in suspendCancellableCoroutine.

suspendCancellableCoroutine { cont ->
		mapOf("name" to "Victor")
	).addOnSuccessListener {
		// parse your data based on what the function returns
		val data = as? Map<String, Any> ?: run {
			cont.resumeWithException(IllegalStateException("Invalid response"))
		cont.resume(data["response"] as String)
	}.addOnFailureListener { exception ->

That way you can make this function suspend on Kotlin and call it normally from your view model/use case/….

If you go ahead and run this code you’ll see that it returns “Hi Victor”

Photo by Annie Spratt on Unsplash