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 is 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 happens 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. Once the Cloud Function returns a response, we must parse it.
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. Such a function may easily deny the request if the user is unauthenticated.
Create a function
We create functions through the onCall
or onRequest
helpers. They both live in the https
sub-package.
import { onRequest, onCall } from "firebase-functions/https"
onCall(async (request) => {
return "OK"
})
specify region in options object
onCall({ region: CLOUD_FUNCTION_REGION }, async (request) => {
return "OK"
})
Activate functions
Firebase checks the package.json
's main
field to find the file that exports the functions. Such file is usually called index.js
{
"main": "lib/index.js"
}
A function is not activated unless it is exported by such file as a named export. Such file usually reexports the function from where it is implemented.
export { requestExamples } from "./requestExamples.js"
export const requestExamples = ...
Write functions in typescript, deploy JS
We must provide functions in JS. The convention is to store TS source code in src/
and transpile it to JS in lib/
.
We may ask the build to happen every time we change TS:
npm run build:watch // runs tsc --watch
Admin SDK
If the function is to use the firestore service.
import { initializeApp } from "firebase-admin/app"
import { getFirestore } from "firebase-admin/firestore"
const app = initializeApp()
const db = getFirestore(app)