Cloud Functions
Cloud Functions are serverless functions: we run code on servers operated by Google.
As it is a secure environment, we can run sensitive tasks: authenticate requests, perform server-side validation, use API keys, make sensitive database writes, and more.
Functions trigger on direct requests, or on events happening in the Firebase ecosystem, such as the registration of new users through Firebase Auth. They can also be triggered by a Cron job.
trigger on direct requests: two options
The first option is to configure and establish a bare-bones REST-API endpoint, called a HTTP function. We configure the endpoint with an Express.js like API.
import { onRequest } from "firebase-functions/https"
The second option is to define a Callable function, a pattern that involves both a server SDK and a client SDK, which together do some heavy lifting on behalf of the developer, such as managing authentication, defining the type of the request's data and response, and offering streaming responses.
import { onCall } from "firebase-functions/https"
select and deploy functions
The main file determines which functions are deployed by default: all the ones that it exports. We determine the main file in package.json. Since it must be a JavaScript file, we refer to the TypeScript compiler output file:
{
"main": "lib/index.js"
}
It is usually a barrel file that re-exports functions from their own files:
export { requestPlayer } from "./requestPlayer.js"
We deploy functions imperatively, all of them or some of them:
firebase deploy --only functions
firebase deploy --only functions:FOO
firebase deploy --only functions:FOO,functions:BAR
We can delete a function imperatively:
firebase functions:delete FOO
configure TypeScript
We use a workflow that transpiles to JS since the functions are deployed as JavaScript functions.
The convention is to store TypeScript code in src/ and transpile towards lib/. The main file is lib/index.js.
tsconfig.json configures the transpilation, targeting the Node.js runtime:
{
"compilerOptions": {
"module": "NodeNext",
"esModuleInterop": true,
"moduleResolution": "nodenext",
"noImplicitReturns": true,
"outDir": "./lib",
"rootDir": "./src",
"sourceMap": true,
"target": "es2022",
"skipLibCheck": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"verbatimModuleSyntax": true
},
"compileOnSave": true,
"include": ["src"]
}
use of the admin SDK
The use of the admin SDK is a natural fit from Cloud functions.