Cloud Functions
Overview
Cloud Functions is a way to run JS code through Node.js on a server managed by Google.
We assume the server being safe from tampering or leaks.
As such, we may perform server-side validation and trigger database mutations. We may store and use API keys and secrets.
Some functions are triggered on HTTP requests. Some functions are triggered by events that happen in the Firebase ecosystem such as the registration of a new user in Firebase Auth.
Two kinds of functions triggered by an HTTP request.
A Firebase HTTP function exposes a regular REST API endpoint. We must craft and send a valid
HTTP request on the client, parse it manually on the server, and parse back the response on the client.
A Firebase Callable function is a pattern where the client SDK and the server SDK do more work as they create and manage the HTTP messages (requests and responses) including managing the authentication data. They may conveniently deny the request if the user is unauthenticated.
Create a function
We build functions with the onCall or onRequest helpers and export them. The helpers live in the https sub-package.
import { onRequest, onCall } from "firebase-functions/https"
onCall function example:
export const requestExamples = onCall(async (request, response) => {
/* ... */
})
Activate functions
Firebase checks the package.json's main field to find the file that exports the functions. Such file is a JS file and is usually called index.js
{
"main": "lib/index.js"
}
A function is not activated unless exported by such file as a named export. It is usually a barrel file, that exports function from where they are implemented.
export { requestExamples } from "./requestExamples.js"
Write functions in typescript, deploy JS
We must provide functions in JS. The convention is to store TS source code in src/ and store the transpiled JS in lib/.
We may make the transpile continuous by watching the typescript files. This helps the emulator to update the cloud functions on the go since it watches the JS functions.
tsc --watch
admin SDK
functions may interact with firebase services such as databases and storage with a privileged role by using the admin SDK.
import { initializeApp } from "firebase-admin/app"
import { getFirestore } from "firebase-admin/firestore"
const app = initializeApp()
const db = getFirestore(app)