Firebase | Testing Firebase Cloud Function Locally with Cloud Function Emulator

Firebase CLI provides a cloud function emulator which can be used to run the Firebase Cloud Function locally before deploying to production. Following are the types of functions which can be emulated.

  • HTTP functions
  • Callable functions
  • Background functions triggered from Authentication, Realtime Database, Cloud Firestore, and Pub/Sub.

We will test a simple http function which we created in the last post.

Creating a Cloud Function Using Firebase CLI and TypeScript.

Following are the steps we will follow:

Install or Update the Firebase CLI

Firebase emulator is included in Firebase CLI, so we need to install it, or update it to the latest version.

npm install -g firebase-tools

Setting Up Admin Credentials for Emulated Functions

If your cloud function requires interaction with Google API or Firebase API via the Firebase Admin SDK then you may need to setup the admin credentials.

Go to the Service Accounts in Google Cloud Platform, under your project.

Select the service account row with Name “App Engine default service account“, and click on Actions button at the right end.

Select Manage Keys.

Click on Add Key drop down button.

Select Create new key.

This will open a modal window.

Choose JSON, from the available key types. This will generate and download the key in json file with key details.

JSON key file will look like following, values are omitted here.

{
  "type": "",
  "project_id": "",
  "private_key_id": "",
  "private_key": "",
  "client_email": "",
  "client_id": "",
  "auth_uri": "",
  "token_uri": "",
  "auth_provider_x509_cert_url": "",
  "client_x509_cert_url": ""
}

Set Google Application Credentials to the JSON file path.

This is required to authenticate to Google API or Firebase API from Firebase Admin SDK.

Execute following from project’s root directory.

set GOOGLE_APPLICATION_CREDENTIALS=path\to\key.json

Run the Firebase Emulator

Now we are ready to start the emulator.

Start the emulator by following command

firebase emulators:start

Emulator will be started and will provide you the function URL.

Call Function URL

Click on provide function URL, and you will receive the response from your function.

Great! We are able to run function locally.

Firebase Emulator UI

You will also be presented with Emulator UI URL.

Open the emulator UI URL in the browser.

In the Emulator screen you will be able to see all the different types of emulators.

You can navigate to Logs, to see any logging by function.

Modify and Test Local Cloud Function

Now let’s update the function.

Change the function response message.

Build the function again, and execute the following from functions folder.

npm run build

Reload the function URL provide by the running emulator and you will see updated response from local function.

When you are happy, you can deploy the function to Firebase as explained in this post.

Firebase | Creating a Cloud Function Using Firebase CLI and TypeScript

Conclusion

The Firebase emulator, which is included in the Firebase CLI, let’s us test the function locally before deploying to the cloud.

In this post we started with installing Firebase CLI and then we setup the Google Account Credential. Google Account Credential requires a JSON file with private key, which was generated in the Google Cloud Platform. Then we started the Firebase emulator and browsed the local function URL and received response from the local function.

Hope you liked this, please share your feedback or any query.

Firebase | Creating a Cloud Function Using Firebase CLI and TypeScript

Overview

Firebase cloud functions let’s you run a piece of code in cloud without managing the servers. This is quite helpful when you just want to manage your code and not to worry about the servers executing the code. This pattern is also known as serverless architecture.

These cloud functions can be triggered by multiple events such as an http request, scheduled time or in response to changes in Realtime Database and perform the intended job.

In this post we will see how we can create a simple Firebase cloud function using Firebase CLI and then deploy it to Firebase. We will use TypeScript to write the function.

Steps for creating the Cloud Function

Let’s create and deploy a Firebase cloud function.

Installing Firebase CLI

Firebase cloud functions are created and deployed using Firebase CLI, so let’s install the Firebase CLI globally. Type following command on command prompt.

npm install -g firebase-tools

Login to Firebase CLI

We need to authenticate to Firebase to create and deploy cloud functions, authenticate to Firebase using following command.

firebase login

This will open a browser window to authenticate.

If you are logged in with another account then you can logout first using following.

firebase logout

Choose the account to login.

Allow, to grant permissions to Firebase CLI.

On Allow following success screen will be presented.

And in command prompt message like following will be logged.

Creating a Firebase Cloud Function Project

Create a directory for the project.

mkdir firebase-function-demo

Change to project directory.

cd firebase-function-demo

Open the directory with Visual Studio code or any other editor.

code .

Initialize Firebase functions project

firebase init functions

Accept the confirmation.

Choose the appropriate option for you. In my case I chose “Use an existing project“, because I have already created the Firebase project.

Next I chose the project from the presented list.

For this example we are going to use the TypeScript, so choose the TypeScript.

Choose Y if you want to use ESLint.

Select Y to install the dependencies.

Your project structure should appear like this so far.

Creating a Cloud Function

We will use the sample helloworld cloud function created by the Firebase CLI for this example.

Open selected index.ts.

index.ts contains commented sample function.

Uncomment the code, and save the file.

File contains one sample http request based cloud function. Which will log following.

"Hello logs!", {structuredData: true}

and return following response.

"Hello from Firebase!"

In the same file more functions can be added, for example we can add another scheduled function like following.

export const scheduledJob = functions.pubsub.schedule("every 5 minutes")
    .onRun(()=>{
      console.log("This will be run every 5 minutes.");
      return null;
    });

This scheduled function will run every five minutes,

cron expression can be added like following to define trigger time for scheduled functions.

export const  scheduledFunctionCrontab = functions.pubsub.schedule('5 11 * * *')
  .timeZone('America/New_York') // Users can choose timezone - default is America/Los_Angeles
  .onRun((context) => {
  console.log('This will be run every day at 11:05 AM Eastern!');
  return null;
});

Deploying cloud function

Let’s deploy the sample code in index.ts to cloud.

Execute the following command on command prompt.

firebase deploy

On successful function deployment, function url will be provided.

Paste the URL in the browser.

and you will get the response like below from cloud function.

Great! Our cloud function is successfully deployed and responding to http request.

Navigate to Firebase project and select functions.

and you should be able to see your cloud function.

You can switch to Logs tab to see the logs of the cloud function.

Congratulations! We have just deployed our first simple cloud function.

Conclusion

In this post we learned how we can create a Firebase Cloud Function and deploy to Firebase. We started with how to install the Firebase CLI globally, and how to authenticate to it. Then we created a template project for cloud function using Firebase CLI and then deployed and tested the cloud function.

Hope you like this!

Please leave your feedback or any query you have.