loading...
Cover image for How to create a Firebase Cloud Function

How to create a Firebase Cloud Function

suvink profile image Suvin Nimnaka ・3 min read

What is a Cloud Function?
This is what the official Firebase website says:

"Cloud Functions for Firebase let you automatically run backend code in response to events triggered by Firebase features and HTTPS requests. Your code is stored in Google's cloud and runs in a managed environment. There's no need to manage and scale your own servers."

You can find more about Cloud Functions here.

So let's dive in and build out first cloud function.

Things you will need

  1. NodeJS Installed(We need npm!).
  2. Firebase CLI tools installed.
  3. Fresh Firebase project (Note down the project name)
  4. Coffee (Probably!)

Okay now go ahead and create a new folder wherever you want and open up a terminal in that folder.
Then execute this:

firebase init

Firebase Init command will take you through a process where you configure your Firebase service. Select Functions from CLI features you want to setup dialog and in the next step choose the project that you noted down earlier when you created a new project. Then select Javascript for the language. And you're done!

Now open your project folder in your fav text editor or IDE. I prefer VSCode!

Now you can see the file structure that Firebase init has created for you.

.
├── firebase.json
├── functions
│   ├── index.json
│   ├── node_modules
│   ├── package-lock.json
│   └── package.json
└── node_modules

Now navigate into functions folder and open up index.js file in your text editor and delete everything inside. Now this is where we are going to code our function.

First we are going to import firebase-functions package

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

Now create a function that takes two parameters "request" and "response" (I'm going to call my function as "firebase_demo") that responds to a http request.

exports.firebase_demo = functions.https.onRequest((request, response) => {

}

This "firebase_demo" function will take in the incoming http request as request and outputs response.

Now we need to specify the status code for the response (Optional, but better to do so). You can find a list of http status codes here.

Lets do that,

exports.pushResults = functions.https.onRequest((req, res) => {
     res.status(200).json({

     })
})

Now you can output your data in JSON format within the response. Lets add some data into the response.

exports.pushResults = functions.https.onRequest((req, res) => {
     res.status(200).json({
         message : "Hello World!"
     })
})

Now this function will respond to an incoming http request with "Hello World!" with a response code of 200 (Which means the request has succeeded).

This is a very basic cloud function but I'm going to add a little extra options here.

I'm going to make my function only respond to POST requests and deny the other type of requests. Let's do that,

exports.pushResults = functions.https.onRequest((req, res) => {
     if(request.method !== "POST"){
        return response.status(400).json({
            message: "Not Allowed"
        })
     }
     res.status(200).json({
         message : "Hello World!"
     })
})

You can see I used status code 400 to respond "Bad Request" if the request method is not a POST request.

Now it's time to deploy. Goto your terminal and from your project folder, execute this,
firebase deploy

Now this will deploy your function into your Firebase project and will provide you with a link to the function which we can use as an endpoint.

Goto API tester (An online service where you can make simple API calls) and paste your endpoint there and set the request method to POST.
You can see it responds with ,

{
   message : "Hello World!"
}

Now change the request method from POST to GET and see the results.

That's it for now. Drop your questions below!

Posted on by:

suvink profile

Suvin Nimnaka

@suvink

🇱🇰 🏝| Single.Mongal 👅| Richmondite™ ❤ Resistance🇱🇰 👣| MUN 👊 Travel Photography📷 | Undergraduate | Airbus is laa

Discussion

markdown guide