Firebase cloud functions Serverless Computing.

Bishal Bhattarai
readytowork, Inc.
Published in
7 min readJul 20, 2022

Firebase is a backend as a service and offers serverless computing. Server-side, such as adding roles, validating the users the code that we don’t want to do from front-end or very hard, so firebase makes a cloud function. The code can interact with all the firebase services and is packaged and deployed to function.

Firebase offers various services:

  • Cloud Firestore
  • Firebase hosting
  • Firebase authentication
  • Firebase cloud storage

Today we will be focusing on cloud function.

Here is a use case example of why we need cloud function.

When a new user signed to add using firebase authentication, But sometimes we don’t want users to access the database from the frontend, We can use cloud functions. Cloud functions run in node js and can write our function in JS and TS.

Let us go to the basic project setup and dive deep into the cloud function.

We need to have a google account to set up the firebase project.

Let’s go to the console to add the project. https://console.firebase.google.com

Go to create a new firebase project.

Create a firebase project

Disable the analytics for now.

The project is being created and will take a while to complete. After completing the project please click on continue to access the project dashboard.

Here is the following screenshot of the dashboard. Now we need to set up a web app to use projects on the web. Please click on </> to add a web app to the project.

Please add the web app name as per business requirement or project and select Firebase hosting to add hosting.

Select next to continue for all the steps adding Firebase SDK, we will add it later in the project, install Firebase CLI, and deploy it to firebase as well. Click on the continue to console.

We will see the dashboard with 1 app label on the project dashboard and also we can see the web app information when we click on the project setting of the web app.

We will now install the Firebase CLI to the local machine. It is very important to have a firebase running from the CLI where we will initialize the firebase project. For this, we need to have node JS installed on the system.

We need to log in to the firebase from the firebase CLI.

firebase login

We need to create a working directory of the project name to initialize the project in a respective project from the CLI.

firebase init

Here we need to select which firebase feature we want. Let’s select firestorm, hosting, and functions. To select we click space and press enter to continue.

First, let us create a database to enable Firestore so that we don’t get errors. While we select the existing firebase project because we have enabled Firestore features as well. Click on Create a database from the Firestore tab on the Firebase console.

Let’s select the production mode too and we have firebase default production rules.

We need to set the Firestore location please select the appropriate location. This cannot be changed later.

Now let’s get back to the terminal where we left. Now we will select from an existing project that we have created.

  1. We now select default rules for the Firestore database and firebase indexes so press enter.
  1. Now its firebase terminal will prompt with the language we can select. It supports TS and JS. so for now select JS. It will still prompt us for ESLint. Type y and enter.
  1. Now it will prompt to installation of the dependencies for the firebase project. type A and hit enter.

The firebase project will be successfully initialized.

Now let’s open in the text editor of your choice. I have used it. vs code for this project.

Let me explain more about the folder and files.

  • functions: we will write firebase functions for cloud functions.
  • public: Everything is deployed to firebase service, currently index and 404
  • .firebaserc: shows which project we are connected to backend
  • firebase.json: it defines property about Firebase.
  • firebase indexes and rules: It defines firestore database rules and firestore index.

Firebase cloud functions:

There are various types of cloud functions:

Background triggers: The functions are triggered by the events of firebase services. Such events are :

  • Database events
  • Auth events
  • Storage events
  • Analytics events

HTTP triggers and callable: These are endpoint functions that are triggered on HTTP requests.

We will make cloud functions under the functions folder and index.js

index.js

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

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Welcome to Firebase Hosting</title>
<!-- update the version number as needed -->
<script defer src="/__/firebase/8.8.0/firebase-app.js"></script>
<!-- include only the Firebase features as you need -->
<script defer src="/__/firebase/8.8.0/firebase-auth.js"></script>
<script defer src="/__/firebase/8.8.0/firebase-database.js"></script>
<script defer src="/__/firebase/8.8.0/firebase-messaging.js"></script>
<script defer src="/__/firebase/8.8.0/firebase-storage.js"></script>
<!-- initialize the SDK after all desired features are loaded -->
<script defer src="/__/firebase/init.js"></script>
</head>
<body>
<div id="message">
<h2>Welcome</h2>
<h1>Firebase Hosting Setup Complete</h1>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
try {
let app = firebase.app();
let features = ['auth', 'database', 'messaging', 'storage'].filter(feature => typeof app[feature] === 'function');
document.getElementById('load').innerHTML = `Firebase SDK loaded with ${features.join(', ')}`;
} catch (e) {
console.error(e);
document.getElementById('load').innerHTML = 'Error loading the Firebase SDK, check the console.';
}
});
</script>
</body>
</html>

To serve the HTTP request or cloud function from the local machine

firebase serve

We get the following output when we hit localhost:5000

To deploy the above site on hosting

firebase deploy --only hosting

To deploy the functions on firebase

firebase deploy --only functions

Firebase runs emulators in the local machine, but we cannot run auth emulators to the local machine.

firebase init emulators

This is a trigger function.

// http auth trigger events (on user create)
exports.newUserSignup = functions.auth.user().onCreate(user => {
console.log("user created ::", user.uid, user.email);
// for background triggers you must return a promise or value
return admin.firestore().collection('users').doc(user.uid).set({
email: user.email,
upvotedOn: []
});
});

Below is an example of an HTTP request callable function.

// http callable function (adding a request)
exports.addRequest = functions.https.onCall((data, context) => {
if (!context.auth) {
throw new functions.https.HttpsError(
'unauthenticated',
"Only authenticate users can add requests"
);
}
if (data.text.length > 30) {
throw new functions.https.HttpsError(
'invalid-argument',
"request must me valid, less than 30 character"
);
}
return admin.firestore().collection('requests').add({
text: data.text,
upvotes: 0,
});
});

This is an example of the HTTP function.

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

To run functions locally

cd functions && firebase emulators:start --only functions

The emulator is served.

On the browser please hit

http://localhost:5001/cloud-function-test-bc0d8/us-central1/helloWorld

We can check the logs in the sections of the log of cloud functions

Code sample: https://github.com/bhattaraibishal50/cloud-functions-test

Thank you 🙇‍♂️ Happy coding 🎉

--

--