DEV Community

Cover image for Firebase Cloud Function HTTP Triggers Explained [2022]
Raja Tamil
Raja Tamil

Posted on • Originally published at softauthor.com

Firebase Cloud Function HTTP Triggers Explained [2022]

By the end of this tutorial, you’ll be able to create, troubleshoot, deploy an HTTP Trigger Cloud Function in Firebase.

1. Install Node.js & NPM

First make sure you install Node and NPM in your computer if you haven’t already.

Go to nodejs.org and download the LTS version of it in your computer.

alt text

Once its downloaded, double click to complete the installation process.

At this stage you’ve successfully installed Node as well as NPM (Node Package Manager).

To verify that, open up the Terminal or Command prompt from you computer and run the following commands:

node -v
npm -v
Enter fullscreen mode Exit fullscreen mode

2. Install Firebase CLI

Open up your terminal or command prompt and run the following command to install Firebase CLI globally in your computer:

npm install -g firebase-tools
Enter fullscreen mode Exit fullscreen mode

It might ask you to enter the admin password for your computer.

3. Authenticate Firebase CLI

Authenticate Firebase CLI by running the following command to login to Firebase:

firebase login
Enter fullscreen mode Exit fullscreen mode

alt text

Once the above command is executed, it will open up the browser window where you can login into your Firebase using your gmail account.

Once it’s authenticated, you’ll have a message saying “Firebase CLI Login successful.”

alt text

Switch back to the Terminal window and you should see the success message there as well.

alt text

4. Initialize Firebase Cloud Function

To initialize the Firebase functions project, run the following command which will create a firebase-debug.log file inside your project project folder.

firebase init functions
Enter fullscreen mode Exit fullscreen mode

It will then give you options and you can choose an existing Firebase project or create new project from Firebase Dashboard.

alt text

If you’ve already created Firebase projects, just select the one that you would like choose.

alt text

Then, choose a language that you would like to write cloud functions on.

alt text

After that, type no to ESLint question and type yes to install dependencies using NPM to the project.

Once the dependencies have been installed successfully, you can see the project folder and files in your project navigator.

alt text

Now, you’re going to write the Cloud Functions inside the index.js file.

You may wonder…

Which triggers are supported by Cloud Functions?

There are two type of Cloud Functions that you can create:

  • HTTP Trigger
  • Database Trigger

5. Create HTTP Trigger Cloud Function

Inside the index.js file, import the Firebase function package and store it in a constant called functions.

const functions = require("firebase-functions");

exports.helloWorld = functions.https.onRequest((request, response) => {
    response.send("Hello from Firebase!");
});
Enter fullscreen mode Exit fullscreen mode

Then, create your first http get function called helloWorld.

So, which language does firebase use?

Well..It’s a Node JS environment, you can literally use Node JS code in there.

Inside the function, send json data to the browser. in this case “Hello from Firebase”.

You can send either HTML data or JSON data to the browser.

6. Deploy Cloud Function

Run the command to deploy the helloWorld functions.

firebase deploy --only functions
Enter fullscreen mode Exit fullscreen mode

alt text

Once it’s deployed successfully, Firebase provides you with the URL that you can run the HTTP function and return data to a browser.

Go to your Firebase Dashboard -> Functions -> Copy the URL under the Trigger column.

alt text

https://us-central1-otti-db3ea.cloudfunctions.net/helloWorld
Enter fullscreen mode Exit fullscreen mode

Paste it in the browser and you can see the text “Hello From Firebase” that I sent from my Cloud Functions.

alt text

7. Enable Billing But FREE

If you get the error message when you run the deploy command, you’re in the Spark plan which means you can use some of the Firebase services for FREE without enabling billing.

However, you’ll need to change your plan to Blaze which enables your billing in order to use Cloud Function.

alt text

Wait…is Cloud Functions not FREE to use?

Technically…yes if you’re using it for development purposes.

The Blaze plan offers you 2 million FREE Cloud Function invocations per month which is more than enough to use it without paying anything – you won’t even come close to having to pay.

To change the plan, go to the Firebase Console Dashboard and choose the Functions tab from the left menu.

alt text

Then, follow the steps to switch to the Blaze plan and enable billing.

8. Show Cloud Function Server Log

Use function logger info to debug our code in case if we get an error.

exports.helloWorld = functions.https.onRequest((request, response) => {
    functions.logger.info("Hello logs!", { structuredData: true });
    response.send("Hello from Firebase!");
});
Enter fullscreen mode Exit fullscreen mode

Once you add the debug code, you’ll need to redeploy the functions again which will take at least 1-2 mins.

Then, run the functions on the browser using the provided URL.

Then, go to the Firebase Dashboard -> Functions -> Log tab and you can check the log message there.

alt text

9. Make An HTTP Request To Firebase Cloud Function

When you type the URL that Firebase provides to the browser, it simply works but when you make an HTTP request from your front-end app, it’ll throw the CORS Error.

http://localhost:5500

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Firebase Cloud Functions</title>
</head>
<body>
    <script>
        fetch("https://us-central1-otti-db3ea.cloudfunctions.net/helloWorld")
            .then(response => {
                console.log(response);
            })
            .catch(error => {
                console.log(error);
            })
    </script>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

alt text

One of the ways to fix the CORS Error permanently is to add a header called “Access-Control-Allow-Origin” to the response.

The value of this header will be the client side URL that you want to grant communication with the HTTP Cloud Function.

Let’s say my client side app is running on localhost:5500.

exports.helloWorld = functions.https.onRequest((request, response) => {
  functions.logger.info("Hello logs!", { structuredData: true });
  response.header("Access-Control-Allow-Origin", "http://localhost:5500");
  response.send("Hello from Firebase!");
});
Enter fullscreen mode Exit fullscreen mode

To check that, redeploy the Cloud Function, which again takes around 1-2 mins.

And, the CORS Error will be gone.

Great!

Waiting for deployment is one of the most painful times that I found.

Luckily, Firebase CLI (that we have installed globally at the beginning of this tutorial) ships with something called “Cloud Functions Emulator”.

10. Test Firebase Cloud Function Locally

To run Firebase Cloud Function locally, use the command below:

firebase emulators:start
Enter fullscreen mode Exit fullscreen mode

This starts running Node.js local server with the localhost URL that you can see in the terminal window which you can see very similar to creating your own Node.js Server side app.

alt text

In my case:

http://localhost:5001/otti-db3ea/us-central1/helloWorld
Enter fullscreen mode Exit fullscreen mode

When you go that URL in your browser, you can see that the Cloud Function is running, but this time locally.

alt text

The good news is when you makes changes in your Cloud Functions code, you do not have to wait to deploy and see the result, which will save a lot of time.

There you have it.

If you’ve any questions or want to add anything to this tutorial, please send me a quick message by commenting below.

Happy Coding!

Top comments (0)