Cloud Functions for firebase are an awesome solutions for running backend code in response of Firebase events and HTTP requests.
As we said before, you can run your backend code in response of Firebase events or HTTP requests.
For instance, pretend that an user is uploading a picture to Firebase Storage. You could easily generate thumbnails from that image and store their path inside Firebase Firestore, a NoSQL realtime database!
You could also write a Serverless REST API with Express.js and deploy it in a metter of seconds… and that’s what we’ll see today!
First of all, let’s fo to the Firebase Admin Console and let’s add a new project .
Then let’s install Firebase Tools on your machine:
Great! Now let’s login in your Firebase account from your command line:
Now you’re ready to bootstrap your function! That’s how you’ll do it:
Now you should have the following folder structure:
We’re ready to write our REST API!
Let’s move inside the
functions directory and install the required dependencies:
Now let’s open the
functions/index.js file and let’s write up our Firebase Cloud Function !
Let’s analyze the code above:
servermodule. here we’ll write our REST server.
apiconstant, which is the Firebase Cloud Function handler: everytime we’ll get an HTTP request, we’ll allocate 2GB of memory and a maximum of 120 seconds for executing the function.
apifunction. It will be reachable over the
Now let’s move inside our
As you can see, we’re creating a standard Express.js app, where we’re basically declaring just an endpoint (
/languages ) and a
* wildcard which will respond with a 404 status page.
Let’s see what’s inside our
Just routes! We’ll delegate to our
/lib/languages/controller.js file the handler for these two routes:
As you can see, we’re just creating two controllers which are taking their data from a local JSON file, but it could have been a database call or any other data source.
getAllLanguages function, we’re just sending back an array of programming languages ridden from the
getLanguage function, we’re doing something a bit more complex:
We’re now ready to test our function locally… and Firebase makes it easy! Let’s just go to the
/functions directory and tipe:
That will bootstrap a local server with an endpoint like this: http://localhost:5000/jsmonday-cms/us-central1/api , where you can test your API! Just try to go to the following URL and see what you get back:
If testing the function locally was easy… deploying it is even easier! Just type the following command:
Your function is now ready to be called from the whole internet!