A step by step guide to use Firebase cloud functions

  • Posted by:

    Sandeep Rao

    • May 11, 2018

    A step by step guide to use Firebase cloud functions

Most apps, whether its on web, mobile or any other OS, needs backend code to help send out information such as notifications or to run long-standing tasks. All this work requires a server.
Firebase Cloud Functions have changed all this by letting you run backend code in the cloud.

Cloud Functions for Firebase lets you automatically run backend code in response to events triggered by Firebase features and HTTPS requests. The  code will be stored in the Google cloud and it runs in a managed environment. There’s no need to manage and scale your own servers.

Things that can be done using Firebase cloud functions

1. Listen to realtime database triggers like onWrite(), onCreate(), onUpdate(), onDelete()
2. Execute intensive / heavyweight work in the cloud instead of in your app (for example, Write a function that updates firebase database nodes etc)
3. Integrate with third party libraries.

Now since we know what firebase cloud functions are, We can write our first firebase cloud function.

Please note that to understand firebase cloud functions, you need to know basics of firebase. 
Installations that are required -
Node js (v6.11.5) is required to create our first firebase cloud function.
My personal favorite is nvm (https://github.com/creationix/nvm) which helps in managing multiple versions of node js.
Set up and initialize Firebase SDK for Cloud Functions
First we need to create a project in Google cloud platform.
Once project is created, install the Firebase CLI via npm (npm comes pre installed with node). Firebase CLI helps in creating the firebase cloud function with a project structure and all boilerplate code :
npm install -g firebase-tools
This command will install firebase globally in your system
Now you need to initialize your project:

1. First we need to log into the browser and authenticate the firebase tool. Run the firebase login.It will open a window in your browser and ask you to login into your account
2. Once logged in, create a directory at any location of your choice for the project.
3. Once directory is created, navigate to the directory.
4. Now run the following command in terminal to initialize the functions firebase init functions
5. In the terminal, you get options to select language to write the functions

It can be either Javascript or Typescript.
I have used typescript in my functions.
Now, once the task is completed in your terminal, let’s write our first function.

Please note that I have only written functions called via HTTP Requests.
You can also write functions which can be called from your app itself using Firebase client SDKs.

Now go to project-directory > functions > src folder you will see a file called index.ts(if selected typescript) or index.js(if selected javascript)
This is the file firebase uses as entry point to deploy any functions.
open this file in editor of your choice (Vscode is personal favorite)
Once opened, paste following code in that-
import * as functions from ‘firebase-functions’;
export const helloWorld = functions.https.onRequest((request, response) => {
response.send(“Hello from Firebase!!!”);
});

Above function does not do much, it return a string ‘Hello from firebase!!!’ whenever it is called.
Now let’s go and deploy this. 

To do so we will have to run firebase deploy from out terminal or cmd(in case you are using windows which you should not :P).
Now you will see some logs in your terminal with a success message
Like Deploy complete!
And next line will have the url of your project →
Project Console: https://console.firebase.google.com/project/oshop-84a73/overview

Similarly, This is the link to your function. Now go to the link and select functions option from right side navigation bar.
You can see your function with link like
https://us-central1-oshop-84a73.cloudfunctions.net/helloWorld
This is the functions you have deployed. If open the link you can see the string you had returned.
Now let’s write a function which listen to a firebase database node change like if some value is inserted inside the node this function will be called
exports.insertEvent = functions.database.ref(‘messages/{:messageId}’).onCreate((snapshot, context) => {
const text = snapshot.val();
const uppercaseText = text.toUpperCase();
return snapshot.ref.parent.child(‘uppercaseText’).set(uppercaseText);
})
This function listen to a node which is `message/{messageId}` and whenever we insert a message it converts the message into uppercase and creates node called upperText.
Now to deploy this we can run
 firebase deploy
Please note that you can run these functions locally for testing using
firebase serve — only functions which will give you a link to run locally something like http://localhost:5000/oshop-84a73/us-central1/helloWorld
Debug your firebase cloud functions using VsCode
When it comes to writing complex functions, debugging become essential. Firebase cloud functions can also be debug using an emulator provided by google itself.

To install function emulator run
npm install -g @google-cloud/functions-emulator
This will install functions-emulator package globally.

Now once installed go to project directory and navigate to functions folder and run
functions-emulator deploy test — trigger-http
Please note `test` is the name of function you are going to deploy.
Now to debug run 
functions-emulator inspect test — trigger-http
It should show a log in terminal like `Debugger for test listening on port 9229`
Now go to vsCode editor and Create a new launch configuration (in the launch.json file) for your project
paste below code in launch.json

 “version”: “0.2 .0”,
 “configurations”: [ { “
 name”: “Inspect Function”,
 “type”: “node2”,
 “request”: “attach”,
 “port”: 9229 
 } ] 
}
Now open the function you want to debug and put breakpoints for the same. 
After adding break point click on the green arrow from debug tag and
now you can debug your code using deployed link.

Conclusion 
Firebase created cloud functions so that developers don’t have to worry about scalability, security, uptime, etc. and can focus primarily on writing code. They run the server and all you have to do is write the JavaScript functions.

With any increase or decrease in traffic or load, the system automatically adjusts the number of virtual servers to meet the required demand and run the function smoothly.

Among the various benefits of Firebase CLoud functions is that you don’t have to maintain your own server, the system is infinitely scalable, you are only charged for the amount of time that your code actually runs, and you have an isolated code base for all your backend code.

Cloud Functions can revolutionize the backend coding process. Do you have any innovative ideas on how to use Firebase Cloud Functions?

Read Next

Terms you need to know in the world of Blockchain and ICO

Posted by:

Om Shanker

Read More Blogs

TOP

Next Blog Last Blog All Blogs