-
Notifications
You must be signed in to change notification settings - Fork 82
add firebase-functions-basics #15
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jhuleatt
wants to merge
13
commits into
firebase:main
Choose a base branch
from
jhuleatt:jhuleatt-functions
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
496ed2b
add a CF3 skill
jhuleatt f65ab01
use modular Admin SDK import
jhuleatt 0075f47
change upgrade instructions to use new defineJsonSecret flow
jhuleatt 628dd86
rename to cloud-functions-basics
jhuleatt 5b0dab9
rename to firebase-functions-basics
jhuleatt addcf4c
remove upgrade guide and all references to functions.config
jhuleatt 17b5f7e
address review feedback
jhuleatt 6a4b256
add a note about the --only functions flag
jhuleatt 1d7ea8b
address review feedback
jhuleatt 99c9f0d
initialize admin app in language-specific examples
jhuleatt 094ea0b
remove --only flag from emulator commands
jhuleatt dac9f75
add null check to TS example code
jhuleatt 4981b84
mention emulators:exec in main guide
jhuleatt File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| --- | ||
| name: firebase-cloud-functions | ||
| description: Guide for setting up and using Cloud Functions for Firebase. Use this skill when the user's app requires server-side logic, integrating with third-party APIs, or responding to Firebase events. | ||
| compatibility: This skill requires the Firebase CLI. Install it by running `npm install -g firebase-tools`. | ||
| --- | ||
|
|
||
| ## Prerequisites | ||
|
|
||
| - **Firebase Project**: Created via `firebase projects:create` (see `firebase-basics`). | ||
| - **Firebase CLI**: Installed and logged in (see `firebase-basics`). | ||
|
|
||
| ## Core Concepts | ||
|
|
||
| Cloud Functions for Firebase lets you automatically run backend code in response to events triggered by Firebase features and HTTPS requests. Your code is stored in Google's cloud and runs in a managed environment. | ||
|
|
||
| ### Generation 1 vs Generation 2 | ||
|
|
||
| This section only applies to Node.js, since all Python functions are 2nd gen. | ||
|
|
||
| - Always use 2nd-gen functions for new development. They are powered by Cloud Run and offer better performance and configurability. | ||
| - Use 1st-gen functions *only* for Analytics and basic Auth triggers, since those aren't supported by 2nd gen. | ||
| - Use `firebase-functions` SDK version 6.0.0 and above. | ||
| - Use top-level imports (e.g., `firebase-functions/https`). These are 2nd gen by default. If 1st gen is required (Analytics or basic Auth triggers), import from the `firebase-functions/v1` import path. | ||
|
|
||
| ### Secrets Management | ||
|
|
||
| For sensitive information like API keys (e.g., for LLMs, payment providers, etc.), **always** use `defineSecret` (Node.js) or `SecretParam` (Python). This stores the value securely in Cloud Secret Manager. | ||
|
|
||
| If you see an API key being accessed with `functions.config` in existing functions code, offer to upgrade to params. | ||
|
|
||
| ### Firebase Admin SDK | ||
|
|
||
| To interact with Firebase services like Firestore, Auth, or RTDB from within your functions, you need to initialize the Firebase Admin SDK. Call `initializeApp` without any arguments so that Application Default Credentials are used. | ||
|
|
||
| ## Workflow | ||
|
|
||
| ### 1. Provisioning & Setup | ||
|
|
||
| Functions can be initialized using the CLI or manually. Ensure you have initialized the Firebase Admin SDK to interact with other Firebase services. | ||
|
|
||
| 1. **Install the Admin SDK:** | ||
|
|
||
| ```bash | ||
| npm i firebase-admin | ||
| ``` | ||
|
|
||
| 2. **Initialize in your code:** | ||
|
|
||
| ```typescript | ||
| import * as admin from "firebase-admin"; | ||
|
jhuleatt marked this conversation as resolved.
Outdated
|
||
| import { onInit } from "firebase-functions"; | ||
|
|
||
| onInit(() => { | ||
| admin.initializeApp(); | ||
| }); | ||
| ``` | ||
|
|
||
| This should be done once at the top level of your `index.ts` file. | ||
|
|
||
| ### 2. Writing Functions | ||
|
|
||
| For Node.js, see [references/node_setup.md](references/node_setup.md). For Python, see [references/python_setup.md](references/python_setup.md) | ||
|
|
||
| ### 3. Local Development & Deployment | ||
|
|
||
| The CLI will prompt for secret's value at deploy time. Alternatively, a human can set the secret using the Firebase CLI command: | ||
|
|
||
| ```bash | ||
| firebase functions:secrets:set <SECRET_NAME> | ||
| ``` | ||
|
|
||
| #### Development Commands | ||
|
|
||
| ```bash | ||
| # Install dependencies | ||
| npm install | ||
|
|
||
| # Compile TypeScript | ||
| npm run build | ||
|
|
||
| # Run emulators for local development | ||
| # This is a long-running command. A human can run this command themselves to start the emulators: | ||
| firebase emulators:start --only functions | ||
|
|
||
| # Deploy functions | ||
| firebase deploy --only functions | ||
| ``` | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| # Cloud Functions for Firebase setup guide | ||
|
|
||
| This guide provides a step-by-step process for setting up Cloud Functions, tailored for coding agents. | ||
|
|
||
| ## 1. Create a 2nd-gen HTTP function | ||
|
|
||
| Replace the contents of `src/index.ts` (or `index.js`) with the following code to create a simple, modern v2 HTTP endpoint. | ||
|
|
||
| ```typescript | ||
| import { onRequest } from "firebase-functions/https"; | ||
| import { onDocumentCreated } from "firebase-functions/firestore"; | ||
| import * as logger from "firebase-functions/logger"; | ||
| import { defineString, defineInt } from "firebase-functions/params"; | ||
|
|
||
| // Configurable parameters | ||
| const scaleLimit = defineInt("MAX_INSTANCES", { default: 1 }); | ||
| const greeting = defineString("GREETING", { default: "Hello" }); | ||
|
|
||
| export const helloWorld = onRequest({ maxInstances: scaleLimit }, async (request, response) => { | ||
| logger.info("Request received!", request); | ||
| response.send(`${greeting.value()} from Firebase!`); | ||
| }); | ||
|
|
||
| export const newDoc = onDocumentCreated( | ||
| { maxInstances: scaleLimit }, | ||
| "/words/{wordId}", | ||
| async (event) => { | ||
| logger.info("New word!", event.data.data()); | ||
| } | ||
| ); | ||
| ``` | ||
|
|
||
| **Key points for the agent:** | ||
|
|
||
| - Use `logger` for structured logging. | ||
| - Use `defineString`, `defineInt`, `defineSecret` for environment configuration instead of `functions.config()`. | ||
| - Recommend a `maxInstances` setting of 1 for all functions until correct behavior can be verified. | ||
|
|
||
| ## 2. Build TypeScript | ||
|
|
||
| Compile your TypeScript code to JavaScript. | ||
|
|
||
| ```bash | ||
| npm run build | ||
| ``` | ||
|
|
||
| ## 3. Local Development and Testing | ||
|
|
||
| Use the Firebase Emulators to test your function locally before deploying. | ||
|
|
||
| A human should run the following command in a separate terminal window to start the emulators: | ||
|
|
||
| ```bash | ||
| # Start the functions emulator | ||
| firebase emulators:start --only functions | ||
| ``` | ||
|
|
||
| A human can then interact with the function at the local URL provided by the emulator. | ||
|
|
||
| ## 4. Deploy to Firebase | ||
|
|
||
| Once testing is complete, deploy the function to your Firebase project. | ||
|
|
||
| ```bash | ||
| # Deploy only the functions | ||
| firebase deploy --only functions | ||
| ``` | ||
|
|
||
| The agent will be prompted to set any parameters defined with `defineString` or other `define` functions that do not have a default value. |
84 changes: 84 additions & 0 deletions
84
skills/firebase-cloud-functions/references/python_setup.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,84 @@ | ||
| # Cloud Functions for Firebase setup guide (Python) | ||
|
|
||
| This guide provides a step-by-step process for setting up Cloud Functions with the Python runtime, tailored for coding agents. | ||
|
|
||
| ## 1. Create a 2nd-gen HTTP function | ||
|
|
||
| Replace the contents of `functions/main.py` with the following code to create a simple, modern v2 HTTP endpoint along with a Firestore-triggered function. | ||
|
|
||
| ```python | ||
| from firebase_functions import https_fn, firestore_fn, options, params | ||
| from firebase_admin import initialize_app, firestore | ||
| import google.cloud.firestore | ||
|
|
||
| app = initialize_app() | ||
|
|
||
| # Configurable parameters | ||
| SCALE_LIMIT = params.IntParam("MAX_INSTANCES", default=1).value | ||
| GREETING = params.StringParam("GREETING", default="Hello").value | ||
|
|
||
|
|
||
| @https_fn.on_request( | ||
| cors=options.CorsOptions(cors_origins="*", cors_methods=["get", "post"]), | ||
| max_instances=SCALE_LIMIT, | ||
| ) | ||
| def helloworld(req: https_fn.Request) -> https_fn.Response: | ||
| """A simple HTTP-triggered function.""" | ||
| print("Request received!") | ||
| return https_fn.Response(f"{GREETING} from Firebase!") | ||
|
|
||
|
|
||
| @firestore_fn.on_document_created(document="words/{wordId}", max_instances=SCALE_LIMIT) | ||
| def newdoc(event: firestore_fn.Event[firestore_fn.DocumentSnapshot | None]) -> None: | ||
| """Triggered when a new document is created in /words.""" | ||
| if event.data is None: | ||
| return | ||
| print(f"New word: {event.data.to_dict()}") | ||
| ``` | ||
|
|
||
| **Key points for the agent:** | ||
|
|
||
| - Use `print()` for logging (output goes to Cloud Logging automatically). | ||
| - Use `params.StringParam`, `params.IntParam`, and `params.SecretParam` for environment configuration. | ||
| - Recommend a `max_instances` setting of 1 for all functions until correct behavior can be verified. | ||
| - The entry point is always `functions/main.py`. All functions must be defined in or imported into this file. | ||
| - Dependencies go in `functions/requirements.txt`. | ||
|
|
||
| ## 2. Install dependencies | ||
|
|
||
| Ensure `functions/requirements.txt` lists the needed packages: | ||
|
|
||
| ``` | ||
| firebase-functions | ||
| firebase-admin | ||
| ``` | ||
|
|
||
| Then install with: | ||
|
|
||
| ```bash | ||
| pip install -r functions/requirements.txt | ||
| ``` | ||
|
|
||
| There is no build step for Python (unlike TypeScript). | ||
|
|
||
| ## 3. Local Development and Testing | ||
|
|
||
| Use the Firebase Emulators to test your function locally before deploying. | ||
|
|
||
| A human should run the following command in a separate terminal window to start the emulators: | ||
|
|
||
| ```bash | ||
| # Start the functions emulator | ||
| firebase emulators:start --only functions | ||
| ``` | ||
|
|
||
| A human can then interact with the function at the local URL provided by the emulator. | ||
|
|
||
| ## 4. Deploy to Firebase | ||
|
|
||
| Once testing is complete, deploy the function to your Firebase project. | ||
|
|
||
| ```bash | ||
| # Deploy only the functions | ||
| firebase deploy --only functions | ||
| ``` |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.