Firebase SDK for Cloud Functions

repository·master·Indexed 21 days ago

https://github.com/firebase/firebase-functions

The firebase-functions SDK provides tools to define and deploy Cloud Functions for Firebase, enabling backend Node.js code to run in response to Firebase platform events. It includes support for Callable functions with HttpsError handling, streaming responses via CallableResponse, Task Queue functions with RetryConfig and RateLimits, and a CLI for local emulation and manifest generation.

Tokens
16.9K
Snippets
49
Records
76
Agent score
77%

What's inside firebase-functions

  1. Use the Firebase SDK for Cloud Functions

    master

    The firebase-functions package allows you to define Cloud Functions that run in a hosted, private, and scalable Node.js environment. You can write code that responds to events from various Firebase services (like Realtime Database, Firestore, or Authentication) and invokes functionality exposed by the Firebase platform.

    To use the SDK, you import specific event triggers from sub-modules (e.g., firebase-functions/database) and use the logger module for structured logging.

    // functions/index.js
    const { onValueCreated } = require("firebase-functions/database");
    const logger = require("firebase-functions/logger");
    const notifyUsers = require("./notify-users");
    
    exports.newPost = onValueCreated({ ref: "/posts/{postId}" }, (event) => {
      logger.info("Received new post with ID:", event.params.postId);
      return notifyUsers(event.data.val());
    });
  2. Run integration tests

    master

    To run the integration tests, use the ./run_tests.sh script.

    WARNING: Running these tests will wipe the contents of the Firebase project(s) provided. Always use disposable Firebase projects for testing.

    The test suite executes multiple cycles: one for Node.js 14 and another for Node.js 16. It relies on a locally installed firebase CLI to deploy functions and requires the gcloud CLI to be installed and authenticated.

    ./run_tests.sh <project_id> [<project_id2>]
  3. Prerequisites for running integration tests

    master

    Before running the integration tests, ensure the following environment requirements are met:

    1. Firebase CLI: Must be installed locally to allow the script to invoke deployment commands.
    2. gcloud CLI: Must be installed and authenticated via gcloud auth login.
    3. Disposable Projects: Since the test wipes project contents, ensure you are targeting non-production Firebase projects.
  4. Generate compiled ProtoBuf

    master

    To decode application/protobuf events, you must generate statically-compiled protobufs. This is done by running the provided update script, which clones necessary Google repositories and uses protobufjs-cli to create the compiled .js and .ts files.

    Prerequisites:

    • The script requires access to the following repositories:
      • https://github.com/googleapis/google-cloudevents
      • https://github.com/googleapis/googleapis
      • https://github.com/google/protobuf
    • The protobufjs-cli package must be available to create the TypeScript/JavaScript files.
    ./update.sh
  5. Run a local Firebase Functions server

    master

    When FUNCTIONS_MANIFEST_OUTPUT_PATH is not set, the CLI starts a local Express server to emulate the Firebase Functions environment.

    Server Configuration

    • Port: The server listens on the port specified by the PORT environment variable. If PORT is not set, it defaults to 8080.

    Control API

    If you set FUNCTIONS_CONTROL_API=true, the server exposes a special endpoint to retrieve the function manifest in YAML-like JSON format:

    • GET /__/functions.yaml: Returns the function stack converted to wire format.

    Lifecycle Management

    The server provides a special endpoint to gracefully shut down the local emulator:

    • GET /__/quitquitquit or POST /__/quitquitquit: Responds with ok and closes the server.

    Example Setup:

    PORT=3000 FUNCTIONS_CONTROL_API=true firebase-functions ./src
  6. Understand the CallableRequest and CallableContext interfaces

    master

    Callable functions (especially in v2) provide a structured way to access request data and security context.

    CallableRequest<T>

    This is the primary object passed to a v2 Callable handler. It contains:

    • data: T: The parameters sent by the client.
    • auth?: AuthData: Verified Firebase Auth information (UID and decoded token).
    • app?: AppCheckData: Verified Firebase App Check information.
    • instanceIdToken?: string: An unverified Instance ID token.
    • rawRequest: Request: The underlying Express request object.
    • acceptsStreaming: boolean: Indicates if the client is requesting a stream (SSE).

    CallableContext

    Used primarily in v1 handlers, it provides access to auth, app, instanceIdToken, and the rawRequest.

  7. Access task metadata via TaskContext

    master

    When writing a Task Queue function, the TaskContext object provides metadata about the specific task execution. This is useful for logging, debugging, or implementing custom retry logic based on previous failures.

    Key properties:

    • id: The unique task ID (the short name).
    • queueName: The name of the queue that triggered the task.
    • retryCount: How many times this task has been retried (starts at 0).
    • executionCount: Total number of times the handler has received a response.
    • scheduledTime: The RFC 3339 string representing when the task was scheduled.
    • previousResponse?: The HTTP response code from the previous retry attempt.
    • retryReason?: The reason provided for the retry.
    • headers?: A record of the raw request headers.
    • auth?: Metadata about the authorization used to invoke the function (contains uid, token, and rawToken).
  8. Understand AIBlockingEvent and data structures

    master

    AI blocking functions receive an AIBlockingEvent<T>, which extends CloudEvent<T>. This event contains metadata about the caller and the AI context:

    Common Metadata Fields:

    • authType: The type of authentication ('app_user', 'unauthenticated', or 'unknown').
    • authId: The unique identifier for the authenticated user.
    • authClaims: Claims associated with the user's authentication.
    • resourceName: The name of the resource being accessed.
    • appId: The Firebase App ID.
    • androidPackageName / iosBundleId: Client identifiers for mobile apps.

    Data Payload (event.data):

    • For beforeGenerateContent: Contains model, template (optional), api (the provider used), and the original request.
    • For afterGenerateContent: Contains all fields from beforeGenerateContent plus the generated response.
  9. Understand the DatabaseEvent structure

    master

    When a Realtime Database function is triggered, it receives a DatabaseEvent object. This object contains metadata about the event and the data itself.

    Event Metadata

    • firebaseDatabaseHost: The domain of the database instance.
    • instance: The instance ID.
    • ref: The full database reference path that triggered the event.
    • location: The location of the database.
    • params: An object containing values from path pattern capture groups (e.g., {uid}).
    • authType: The type of principal that triggered the event ("app_user", "admin", "unauthenticated", or "unknown").
    • authId: The unique identifier of the principal (if available).

    Event Data

    • For onValueCreated, onValueUpdated, and onValueDeleted (via onValueWritten): The data property is a Change<DataSnapshot> containing before and after snapshots.
    • For onValueCreated and onValueDeleted (via onValueWritten): The data property is a single DataSnapshot representing the state at that path.
  10. Understand AuthType in Data Connect events

    master

    The authType field in a DataConnectEvent identifies the type of principal that triggered the mutation. This is useful for implementing permission-based logic within your functions.

    Possible values for AuthType:

    • app_user: An end user of an application.
    • admin: An admin user of an application (e.g., an impersonator using the Admin SDK).
    • unknown: A general type for principals that do not fall into the other categories.
  11. Trigger functions on Realtime Database changes

    master

    You can trigger Cloud Functions based on specific events in your Firebase Realtime Database. There are four primary event handlers available:

    • onValueCreated: Triggers when data is newly created at a specific path.
    • onValueUpdated: Triggers when existing data at a path is modified.
    • onValueDeleted: Triggers when data at a path is removed.
    • onValueWritten: Triggers on any of the above (create, update, or delete).

    Each handler accepts either a string representing the database reference path or a ReferenceOptions object for advanced configuration. When using path patterns (e.g., /users/{uid}), the captured segments are available in the params property of the event object.

    import { onValueCreated } from 'firebase-functions/v2/database';
    
    export const myCreatedFunction = onValueCreated('/users/{uid}', (event) => {
      const uid = event.params.uid;
      const snapshot = event.data;
      console.log(`User ${uid} created with data:`, snapshot.val());
    });