Cloud Functions are about serverless event-driven code. Serverless applications have become increasingly popular in recent years. Serverless computing offers several advantages over traditional server-centric infrastructure: avoids the need for server provisioning, offers easier setup, greater scalability, more flexibility, and quicker time to release. With serverless architectures, developers can focus on writing and testing the application.
To build our RESTful API using serverless technology, we use RTDB (i.e. Firebase realtime database) and Firebase cloud functions, which can be wired to respond directly to HTTP requests.
First, create a Firebase project in Firebase console.
We are going to be using node as well as express to host the server-side code and program in server-side Typescript. We also need to write functions locally with the help of firebase CLI. To set up the environment in Linux, follow these steps:
In Linux terminal, install nvm:
$ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | Restart Terminal once before starting using NVM.
Check in the terminal:
$ command -v nvmSample output: nvm
Install Node.js and npm:
$ nvm install v12.18.1Check in the terminal:
$ node --versionSample output: v12.18.1
$ npm --versionSample output: 6.14.5
Install Firebase CLI
$ npm install -g firebase-toolsCan check its version
$ firebase --versionIn Linux terminal, run:
$ mkdir folderName
$ cd folderName/
$ firebase login -> “Y” -> log in and allow access
$ firebase initSelect “Database, Functions, Hosting, Emulators” Select “Use an existing project” -> input projectID
Select Typescript
Type “Y” except “Configure as a single-page app (rewrite all urls to /index.html)?”
Select "Functions, Database, Hosting" for emulators
Should see ✔ Firebase initialization complete!
Then, run:
$ cd folderName/functions
$ npm install --save express body-parserThere are three important things under the functions directory.
index.jsis a Javascript file where we define all the functions.Package.jsonis a Json file used by node, containing modules and their dependencies (e.g. Firebase Admin, Firebase functions) for the usage of the functions.node_modulesis a folder where NPM installed those modules during the setup.
Run:
$ npm run lint
$ npm run build
$ firebase emulators:startCheck the output for the URL:
Three different ways to check the output:
a. Use curl in the terminal
b. Enter the url in a browser
c. Use Postman
Run:
$ firebase deployCheck the output for the URL:
$ curl https://step95-2020.firebaseapp.com/ROUTE -H "Authorization: bearer $(gcloud auth print-identity-token)"