### Example POSTINSTALL.md for a Realtime Database Extension Source: https://firebase.google.com/docs/extensions/publishers/get-started This file guides users on how to test and use the extension after installation, including monitoring recommendations. It can reference user parameters like `${param:PROJECT_ID}`. ```Markdown ### See it in action You can test out this extension right away! 1. Go to your [Realtime Database dashboard](https://console.firebase.google.com/project/${param:PROJECT_ID}/database/${param:PROJECT_ID}/data) in the Firebase console. 1. Add a message string to a path that matches the pattern `${param:MESSAGE_PATH}`. 1. In a few seconds, you'll see a sibling node named `upper` that contains the message in upper case. ### Using the extension We recommend adding data by pushing -- for example, `firebase.database().ref().push()` -- because pushing assigns an automatically generated ID to the node in the database. During retrieval, these nodes are guaranteed to be ordered by the time they were added. Learn more about reading and writing data for your platform (iOS, Android, or Web) in the [Realtime Database documentation](https://firebase.google.com/docs/database/). ### Monitoring As a best practice, you can [monitor the activity](https://firebase.google.com/docs/extensions/manage-installed-extensions#monitor) of your installed extension, including checks on its health, usage, and logs. ``` -------------------------------- ### Example PREINSTALL.md for a Realtime Database Extension Source: https://firebase.google.com/docs/extensions/publishers/get-started This file provides pre-installation information, including a brief description of the extension's function, expected database layout, additional setup steps, and billing implications. ```Markdown Use this extension to automatically convert strings to upper case when added to a specified Realtime Database path. This extension expects a database layout like the following example: "messages": { MESSAGE_ID: { "original": MESSAGE_TEXT }, MESSAGE_ID: { "original": MESSAGE_TEXT }, } When you create new string records, this extension creates a new sibling record with upper-cased text: MESSAGE_ID: { "original": MESSAGE_TEXT, "upper": UPPERCASE_MESSAGE_TEXT, } #### Additional setup Before installing this extension, make sure that you've [set up Realtime Database](https://firebase.google.com/docs/database/quickstart) in your Firebase project. #### Billing To install an extension, your project must be on the [Blaze (pay as you go) plan](https://firebase.google.com/pricing). - This extension uses other Firebase and Google Cloud Platform services, which have associated charges if you exceed the service's no-cost tier: - Realtime Database - Cloud Functions (Node.js 10+ runtime) [See FAQs](/docs/functions/faq-and-troubleshooting#extensions-pricing) - If you enable events, [Eventarc fees apply](https://cloud.google.com/eventarc/pricing). ``` -------------------------------- ### Initialize Terraform Configuration Source: https://firebase.google.com/docs/projects/terraform/get-started Run this command to initialize the configuration directory and install the Google Terraform provider. This is required for the first-time setup. ```bash terraform init ``` -------------------------------- ### Create Example City and Landmark Data in C# Source: https://firebase.google.com/docs/firestore/enterprise/query-data-core This snippet initializes a Firestore database and populates it with example city documents in the 'cities' collection, along with associated landmark documents in subcollections for each city. This data setup is essential for demonstrating various Firestore query capabilities. ```csharp private static async Task QueryCreateExamples(string project) { FirestoreDb db = FirestoreDb.Create(project); // Note: the extra braces here are just to allow multiple citiesRef local variables. { CollectionReference citiesRef = db.Collection("cities"); await citiesRef.Document("SF").SetAsync(new Dictionary { { "Name", "San Francisco" }, { "State", "CA" }, { "Country", "USA" }, { "Capital", false }, { "Population", 860000 }, { "Density", 18000 }, { "Regions", new[] {"west_coast", "norcal"} } }); await citiesRef.Document("LA").SetAsync(new Dictionary { { "Name", "Los Angeles" }, { "State", "CA" }, { "Country", "USA" }, { "Capital", false }, { "Population", 3900000 }, { "Density", 8300 }, { "Regions", new[] {"west_coast", "socal"} } }); await citiesRef.Document("DC").SetAsync(new Dictionary { { "Name", "Washington D.C." }, { "State", null }, { "Country", "USA" }, { "Capital", true }, { "Population", 680000 }, { "Density", 11300 }, { "Regions", new[] {"east_coast"} } }); await citiesRef.Document("TOK").SetAsync(new Dictionary { { "Name", "Tokyo" }, { "State", null }, { "Country", "Japan" }, { "Capital", true }, { "Population", 9000000 }, { "Density", 16000 }, { "Regions", new[] {"kanto", "honshu"} } }); await citiesRef.Document("BJ").SetAsync(new Dictionary { { "Name", "Beijing" }, { "State", null }, { "Country", "China" }, { "Capital", true }, { "Population", 21500000 }, { "Density", 3500 }, { "Regions", new[] {"jingjinji", "hebei"} } }); Console.WriteLine("Added example cities data to the cities collection."); } { CollectionReference citiesRef = db.Collection("cities"); await citiesRef.Document("SF").Collection("landmarks").Document() .SetAsync(new { Name = "Golden Gate Bridge", Type = "bridge" }); await citiesRef.Document("SF").Collection("landmarks").Document() .SetAsync(new { Name = "Legion of Honor", Type = "museum" }); await citiesRef.Document("LA").Collection("landmarks").Document() .SetAsync(new { Name = "Griffith Park", Type = "park" }); await citiesRef.Document("DC").Collection("landmarks").Document() .SetAsync(new { Name = "Lincoln Memorial", Type = "memorial" }); await citiesRef.Document("DC").Collection("landmarks").Document() .SetAsync(new { Name = "National Air And Space Museum", Type = "museum" }); await citiesRef.Document("TOK").Collection("landmarks").Document() .SetAsync(new { Name = "Ueno Park", Type = "park" }); await citiesRef.Document("TOK").Collection("landmarks").Document() .SetAsync(new { Name = "National Museum of Nature and Science", Type = "museum" }); await citiesRef.Document("BJ").Collection("landmarks").Document() .SetAsync(new { Name = "Jingshan Park", Type = "park" }); await citiesRef.Document("BJ").Collection("landmarks").Document() .SetAsync(new { Name = "Beijing Ancient Observatory", Type = "museum" }); } } ``` -------------------------------- ### Complete Multi-Factor Enrollment Flow (Kotlin & Java) Source: https://firebase.google.com/docs/auth/android/multi-factor This comprehensive example demonstrates the full flow for enrolling a second authentication factor, from getting the multi-factor session to completing the enrollment. ```Kotlin val multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential) user.multiFactor.session .addOnCompleteListener { task -> if (task.isSuccessful) { val multiFactorSession = task.result val phoneAuthOptions = PhoneAuthOptions.newBuilder() .setPhoneNumber(phoneNumber) .setTimeout(30L, TimeUnit.SECONDS) .setMultiFactorSession(multiFactorSession) .setCallbacks(callbacks) .build() // Send SMS verification code. PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions) } } // Ask user for the verification code. val credential = PhoneAuthProvider.getCredential(verificationId, verificationCode) val multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential) // Complete enrollment. FirebaseAuth.getInstance() .currentUser ?.multiFactor ?.enroll(multiFactorAssertion, "My personal phone number") ?.addOnCompleteListener { // ... } ``` ```Java MultiFactorAssertion multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential); user.getMultiFactor().getSession() .addOnCompleteListener( new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { if (task.isSuccessful()) { MultiFactorSession multiFactorSession = task.getResult(); PhoneAuthOptions phoneAuthOptions = PhoneAuthOptions.newBuilder() .setPhoneNumber(phoneNumber) .setTimeout(30L, TimeUnit.SECONDS) .setMultiFactorSession(multiFactorSession) .setCallbacks(callbacks) .build(); // Send SMS verification code. PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions); } } }); // Ask user for the verification code. PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, verificationCode); MultiFactorAssertion multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential); // Complete enrollment. FirebaseAuth.getInstance() .getCurrentUser() .getMultiFactor() .enroll(multiFactorAssertion, "My personal phone number") .addOnCompleteListener( new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { // ... } }); ``` -------------------------------- ### Boilerplate Monitoring Section for POSTINSTALL Source: https://firebase.google.com/docs/extensions/publishers/user-documentation Recommended boilerplate text to include in the POSTINSTALL file, guiding users on how to monitor their installed extension's activity, health, usage, and logs. ```markdown Monitoring As a best practice, you can [monitor the activity](https://firebase.google.com/docs/extensions/manage-installed-extensions_community#monitor) of your installed extension, including checks on its health, usage, and logs. ``` -------------------------------- ### Retrieve Firebase Installation ID Source: https://firebase.google.com/docs/projects/manage-installations Use this snippet to get the unique Firebase Installation ID for the current app instance, which can be used for identifying specific installations. ```Swift do { let id = try await Installations.installations().installationID() print("Installation ID: \(id)") } catch { print("Error fetching id: \(error)") } AppDelegate.swift ``` ```Objective-C [[FIRInstallations installations] installationIDWithCompletion:^(NSString *identifier, NSError *error) { if (error != nil) { NSLog(@"Error fetching Installation ID %@", error); return; } NSLog(@"Installation ID: %@", identifier); }]; ObjCSnippets.m ``` ```Java FirebaseInstallations.getInstance().getId() .addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { if (task.isSuccessful()) { Log.d("Installations", "Installation ID: " + task.getResult()); } else { Log.e("Installations", "Unable to get Installation ID"); } } }); MainActivity.java ``` ```Kotlin FirebaseInstallations.getInstance().id.addOnCompleteListener { task -> if (task.isSuccessful) { Log.d("Installations", "Installation ID: " + task.result) } else { Log.e("Installations", "Unable to get Installation ID") } } MainActivity.kt ``` ```JavaScript const installationId = await firebase.installations().getId(); console.log(installationId); index.js ``` ```Dart String id = await FirebaseInstallations.instance.getId(); ``` -------------------------------- ### Example: Apply 'blog' Target to 'myapp-blog' Site Source: https://firebase.google.com/docs/hosting/multisites This example applies the target name 'blog' to the Hosting site identified as 'myapp-blog'. ```bash firebase target:apply hosting **blog myapp-blog** ``` -------------------------------- ### Install Firebase Admin Go SDK Source: https://firebase.google.com/docs/admin/setup Installs the Firebase Admin Go SDK using the go get utility, allowing for installation of the latest or a specific version. ```bash # Install the latest version: go get firebase.google.com/go/v4@latest # Or install a specific version: go get firebase.google.com/go/v4@4.20.0 ``` -------------------------------- ### Delete Firebase Installation ID (Android) Source: https://firebase.google.com/docs/projects/manage-installations Deletes the Firebase Installation ID using the `FirebaseInstallations` API for Android, with examples in Java and Kotlin. ```Java FirebaseInstallations.getInstance().delete() .addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { if (task.isSuccessful()) { Log.d("Installations", "Installation deleted"); } else { Log.e("Installations", "Unable to delete Installation"); } } }); MainActivity.java ``` ```Kotlin FirebaseInstallations.getInstance().delete().addOnCompleteListener { task -> if (task.isComplete) { Log.d("Installations", "Installation deleted") } else { Log.e("Installations", "Unable to delete Installation") } } MainActivity.kt ``` -------------------------------- ### Set Up Example Data for Collection Group Query (Node.js) Source: https://firebase.google.com/docs/firestore/pipelines/stages/input/collection-group Creates sample documents in various 'departments' subcollections to demonstrate the `collectionGroup` stage. ```Node.js await db.collection("cities/SF/departments").doc("building").set({name: "SF Building Deparment", employees: 750}); await db.collection("cities/NY/departments").doc("building").set({name: "NY Building Deparment", employees: 1000}); await db.collection("cities/CHI/departments").doc("building").set({name: "CHI Building Deparment", employees: 900}); await db.collection("cities/NY/departments").doc("finance").set({name: "NY Finance Deparment", employees: 1200}); ``` -------------------------------- ### Example: Apply 'app' Target to 'myapp-app' Site Source: https://firebase.google.com/docs/hosting/multisites This example applies the target name 'app' to the Hosting site identified as 'myapp-app'. ```bash firebase target:apply hosting **app myapp-app** ``` -------------------------------- ### Get All Documents from a Collection (Web - JavaScript Promise) Source: https://firebase.google.com/docs/firestore/quickstart This example uses the promise-based `get()` method on a collection reference to retrieve and log all documents. ```JavaScript db.collection("users").get().then((querySnapshot) => { querySnapshot.forEach((doc) => { console.log(`${doc.id} => ${doc.data()}`); }); }); test.firestore.js ``` -------------------------------- ### Create Go Application Directory Source: https://firebase.google.com/docs/hosting/cloud-run Commands to create and enter the `helloworld-go` directory for the Go sample application. ```bash mkdir helloworld-go cd helloworld-go ``` -------------------------------- ### Kotlin data class mapping for Firestore Source: https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/PropertyName Examples of using PropertyName in Kotlin. Use both @get and @set for read/write properties, or just @get for read-only/write-only properties. ```kotlin data class Pojo(@get:PropertyName("my_foo") @set:PropertyName("my_foo") var foo: String? = null) { constructor() : this(null) // Used by Firestore to create new instances } ``` ```kotlin data class Pojo(@get:PropertyName("my_foo") val foo: String? = null) ``` -------------------------------- ### listTenants (pageToken) Source: https://firebase.google.com/docs/reference/admin/java/reference/com/google/firebase/auth/multitenancy/TenantManager Gets a page of tenants starting from the specified `pageToken`. ```APIDOC ## public ListTenantsPage listTenants (String pageToken) ### Description Gets a page of tenants starting from the specified `pageToken`. ### Method Java Method ### Endpoint TenantManager.listTenants ### Parameters #### Query Parameters - **pageToken** (String) - Optional - The token to start listing tenants from. ### Response #### Success Response - **ListTenantsPage** (ListTenantsPage) - A page of tenants. ``` -------------------------------- ### Set up sample city documents (Node.js) Source: https://firebase.google.com/docs/firestore/pipelines/stages/input/documents Creates three documents in the 'cities' collection for demonstration purposes. ```Node.js await db.collection("cities").doc("SF").set({name: "San Francsico", state: "California"}); await db.collection("cities").doc("NYC").set({name: "New York City", state: "New York"}); await db.collection("cities").doc("CHI").set({name: "Chicago", state: "Illinois"}); ``` -------------------------------- ### README Installation Information Template Source: https://firebase.google.com/docs/extensions/publishers/user-documentation Use this template to add standard installation instructions to your extension's README, covering both Console and Firebase CLI methods. ```markdown --- ## 🧩 Install this extension ### Console [![Install this extension in your Firebase project](https://www.gstatic.com/mobilesdk/210513_mobilesdk/install-extension.png "Install this extension in your Firebase project")][install-link] [install-link]: https://console.firebase.google.com/project/_/extensions/install?ref=publisher_id/extension_name ### Firebase CLI ```bash firebase ext:install publisher_id/extension_name --project=[your-project-id] ``` > Learn more about installing extensions in the Firebase Extensions documentation: > [console](https://firebase.google.com/docs/extensions/install-extensions?platform=console), > [CLI](https://firebase.google.com/docs/extensions/install-extensions?platform=cli) --- ``` -------------------------------- ### Example Twitter REST API Call Source: https://firebase.google.com/docs/auth/ios/twitter-login Demonstrates how to call the Twitter REST API, for example, to get basic profile information, by passing the access token in the Authorization header. ```HTTP https://api.twitter.com/labs/1/users?usernames=TwitterDev ``` -------------------------------- ### ListOidcProviderConfigsAsync(ListProviderConfigsOptions options) Source: https://firebase.google.com/docs/reference/admin/dotnet/class/firebase-admin/auth/abstract-firebase-auth Gets an async enumerable to iterate or page through OIDC provider configurations starting from the specified page token. If the page token is null or unspecified, iteration starts from the first page. ```APIDOC ## ListOidcProviderConfigsAsync ### Signature ```csharp PagedAsyncEnumerable< AuthProviderConfigs< OidcProviderConfig >, OidcProviderConfig > ListOidcProviderConfigsAsync( ListProviderConfigsOptions options ) ``` ### Description Gets an async enumerable to iterate or page through OIDC provider configurations starting from the specified page token. If the page token is null or unspecified, iteration starts from the first page. See Page Streaming for more details on how to use this API. ### Parameters - **options** (ListProviderConfigsOptions) - Optional - The options to control the starting point and page size. Pass null to list from the beginning with default settings. ### Returns A PagedAsyncEnumerable, OidcProviderConfig> instance. ``` -------------------------------- ### Set Up Firebase Emulator Suite Source: https://firebase.google.com/docs/emulator-suite/install_and_configure Execute this command to configure the Emulator Suite, select desired emulators, download binaries, and customize port settings. ```bash firebase init emulators ``` -------------------------------- ### Example: Export 'restaurants' and 'reviews' collections Source: https://firebase.google.com/docs/firestore/enterprise/export-import-mongodb An example demonstrating how to export specific collections like 'restaurants' and 'reviews' from the 'cymbal' database to a Cloud Storage bucket. ```bash gcloud firestore export gs://[BUCKET_NAME] \ --collection-ids=restaurants,reviews \ --database='cymbal' ``` -------------------------------- ### Get PlayIntegrityAppCheckProviderFactory Singleton Instance (Java) Source: https://firebase.google.com/docs/reference/android/com/google/firebase/appcheck/playintegrity/PlayIntegrityAppCheckProviderFactory Retrieves the singleton instance of `PlayIntegrityAppCheckProviderFactory` for installation into a `FirebaseAppCheck` instance. ```java public static @NonNull PlayIntegrityAppCheckProviderFactory getInstance() ``` -------------------------------- ### Connect to Live API and Start Audio Conversation (Java) Source: https://firebase.google.com/docs/ai-logic/live-api Create a LiveModel instance, configure it for audio response, and connect to a live session. Use a callback to start the audio conversation upon successful connection. ```Java ExecutorService executor = Executors.newFixedThreadPool(1); // Initialize the Gemini Developer API backend service // Create a `liveModel` instance with a model that supports the Live API LiveGenerativeModel lm = FirebaseAI.getInstance(GenerativeBackend.googleAI()).liveModel( "gemini-2.5-flash-native-audio-preview-12-2025", // Configure the model to respond with audio new LiveGenerationConfig.Builder() .setResponseModality(ResponseModality.AUDIO) .build() ); LiveModelFutures liveModel = LiveModelFutures.from(lm); ListenableFuture sessionFuture = liveModel.connect(); Futures.addCallback(sessionFuture, new FutureCallback() { @Override public void onSuccess(LiveSession ses) { LiveSessionFutures session = LiveSessionFutures.from(ses); session.startAudioConversation(); } @Override public void onFailure(Throwable t) { // Handle exceptions } }, executor); ``` -------------------------------- ### listTenants (pageToken, maxResults) Source: https://firebase.google.com/docs/reference/admin/java/reference/com/google/firebase/auth/multitenancy/TenantManager Gets a page of tenants starting from the specified `pageToken` with a maximum number of results. ```APIDOC ## public ListTenantsPage listTenants (String pageToken, int maxResults) ### Description Gets a page of tenants starting from the specified `pageToken`. ### Method Java Method ### Endpoint TenantManager.listTenants ### Parameters #### Query Parameters - **pageToken** (String) - Optional - The token to start listing tenants from. - **maxResults** (int) - Optional - The maximum number of tenants to return per page. ### Response #### Success Response - **ListTenantsPage** (ListTenantsPage) - A page of tenants. ``` -------------------------------- ### Example Output: List Running Emulators Source: https://firebase.google.com/docs/emulator-suite/install_and_configure This JSON object shows the typical response when listing running emulators, detailing the hub and individual emulator configurations. ```json { "hub":{ "name": "hub", "host": "localhost", "port": 4400 }, "functions": { "name": "functions", "host": "localhost", "port": 5001 } "firestore": { "name": "firestore", "host": "localhost", "port": 8080 } } ``` -------------------------------- ### Get All Documents in a Collection (Java - Server/Admin SDK) Source: https://firebase.google.com/docs/firestore/enterprise/get-data-core This Java example for server environments (Admin SDK) shows how to asynchronously retrieve all documents from a Firestore collection. It blocks on the future to get the response and then iterates through the documents. ```Java // asynchronously retrieve all documents ApiFuture future = db.collection("cities").get(); // future.get() blocks on response List documents = future.get().getDocuments(); for (QueryDocumentSnapshot document : documents) { System.out.println(document.getId() + " => " + document.toObject(City.class)); } ``` -------------------------------- ### Log Promotion Events in Objective-C Source: https://firebase.google.com/docs/analytics/measure-ecommerce This example demonstrates how to prepare promotion parameters and log `view_promotion` and `select_promotion` events in Objective-C. ```Objective-C // Prepare promotion parameters NSMutableDictionary *promoParams = [@{ kFIRParameterPromotionID: @"T12345", kFIRParameterPromotionName: @"Summer Sale", kFIRParameterCreativeName: @"summer2020_promo.jpg", kFIRParameterCreativeSlot: @"featured_app_1", kFIRParameterLocationID: @"HERO_BANNER", } mutableCopy]; // Add items promoParams[kFIRParameterItems] = @[jeggings]; // Log event when promotion is displayed [FIRAnalytics logEventWithName:kFIREventViewPromotion parameters:promoParams]; // Log event when promotion is selected [FIRAnalytics logEventWithName:kFIREventSelectPromotion parameters:promoParams]; AnalyticsHelper.m ``` -------------------------------- ### getInstance Source: https://firebase.google.com/docs/reference/android/com/google/firebase/appcheck/recaptcha/RecaptchaAppCheckProviderFactory Gets a singleton instance of `RecaptchaAppCheckProviderFactory` for installation into a `FirebaseAppCheck` instance. This allows for consistent configuration across the application. ```APIDOC ## getInstance ### Description Gets an instance of this class for installation into a `FirebaseAppCheck` instance. ### Method `public static @NonNull RecaptchaAppCheckProviderFactory getInstance()` ### Parameters #### Method Parameters - No parameters. ``` -------------------------------- ### ListTenantsAsync(ListTenantsOptions options) Source: https://firebase.google.com/docs/reference/admin/dotnet/class/firebase-admin/auth/multitenancy/tenant-manager Gets an async enumerable to iterate or page through tenants starting from the specified page token. ```APIDOC ## ListTenantsAsync(ListTenantsOptions options) ### Description Gets an async enumerable to iterate or page through tenants starting from the specified page token. ### Method Signature `PagedAsyncEnumerable< TenantsPage, Tenant > ListTenantsAsync(ListTenantsOptions options)` ### Parameters - **options** (ListTenantsOptions) - Required - Options for listing tenants, such as page token and page size. ### Returns `PagedAsyncEnumerable< TenantsPage, Tenant >` - An async enumerable that can be used to iterate or page through `Tenant` objects. ``` -------------------------------- ### Initialize Firebase Hosting for a New Project Source: https://firebase.google.com/docs/hosting/frameworks/flutter Run this command to start the Firebase project initialization process, which will prompt you to configure hosting and framework settings. ```bash firebase init hosting ``` -------------------------------- ### ListUsersAsync Source: https://firebase.google.com/docs/reference/admin/dotnet/class/firebase-admin/auth/abstract-firebase-auth Gets an async enumerable to iterate or page through users starting from the specified page token. If the page token is null or unspecified, iteration starts from the first page. See Page Streaming for more details on how to use this API. ```APIDOC ## PagedAsyncEnumerable< ExportedUserRecords, ExportedUserRecord > ListUsersAsync(ListUsersOptions options) ### Description Gets an async enumerable to iterate or page through users starting from the specified page token. If the page token is null or unspecified, iteration starts from the first page. See Page Streaming for more details on how to use this API. ### Parameters - **options** (ListUsersOptions) - The options to control the starting point and page size. Pass null to list from the beginning with default settings. ### Returns A PagedAsyncEnumerable{ExportedUserRecords, ExportedUserRecord} instance. ``` -------------------------------- ### Set up example city data in Firestore Source: https://firebase.google.com/docs/firestore/enterprise/query-data-core Use these code examples to populate a Firestore 'cities' collection with sample documents, which can then be used for demonstrating various query operations. ```kotlin val cities = db.collection("cities") val data1 = hashMapOf( "name" to "San Francisco", "state" to "CA", "country" to "USA", "capital" to false, "population" to 860000, "regions" to listOf("west_coast", "norcal"), ) cities.document("SF").set(data1) val data2 = hashMapOf( "name" to "Los Angeles", "state" to "CA", "country" to "USA", "capital" to false, "population" to 3900000, "regions" to listOf("west_coast", "socal"), ) cities.document("LA").set(data2) val data3 = hashMapOf( "name" to "Washington D.C.", "state" to null, "country" to "USA", "capital" to true, "population" to 680000, "regions" to listOf("east_coast"), ) cities.document("DC").set(data3) val data4 = hashMapOf( "name" to "Tokyo", "state" to null, "country" to "Japan", "capital" to true, "population" to 9000000, "regions" to listOf("kanto", "honshu"), ) cities.document("TOK").set(data4) val data5 = hashMapOf( "name" to "Beijing", "state" to null, "country" to "China", "capital" to true, "population" to 21500000, "regions" to listOf("jingjinji", "hebei"), ) cities.document("BJ").set(data5) ``` ```java CollectionReference cities = db.collection("cities"); Map data1 = new HashMap<>(); data1.put("name", "San Francisco"); data1.put("state", "CA"); data1.put("country", "USA"); data1.put("capital", false); data1.put("population", 860000); data1.put("regions", Arrays.asList("west_coast", "norcal")); cities.document("SF").set(data1); Map data2 = new HashMap<>(); data2.put("name", "Los Angeles"); data2.put("state", "CA"); data2.put("country", "USA"); data2.put("capital", false); data2.put("population", 3900000); data2.put("regions", Arrays.asList("west_coast", "socal")); cities.document("LA").set(data2); Map data3 = new HashMap<>(); data3.put("name", "Washington D.C."); data3.put("state", null); data3.put("country", "USA"); data3.put("capital", true); data3.put("population", 680000); data3.put("regions", Arrays.asList("east_coast")); cities.document("DC").set(data3); Map data4 = new HashMap<>(); data4.put("name", "Tokyo"); data4.put("state", null); data4.put("country", "Japan"); data4.put("capital", true); data4.put("population", 9000000); data4.put("regions", Arrays.asList("kanto", "honshu")); cities.document("TOK").set(data4); Map data5 = new HashMap<>(); data5.put("name", "Beijing"); data5.put("state", null); data5.put("country", "China"); data5.put("capital", true); data5.put("population", 21500000); data5.put("regions", Arrays.asList("jingjinji", "hebei")); cities.document("BJ").set(data5); ``` ```dart final cities = db.collection("cities"); final data1 = { "name": "San Francisco", "state": "CA", "country": "USA", "capital": false, "population": 860000, "regions": ["west_coast", "norcal"] }; cities.doc("SF").set(data1); final data2 = { "name": "Los Angeles", "state": "CA", "country": "USA", "capital": false, "population": 3900000, "regions": ["west_coast", "socal"], }; cities.doc("LA").set(data2); final data3 = { "name": "Washington D.C.", "state": null, "country": "USA", "capital": true, "population": 680000, "regions": ["east_coast"] }; cities.doc("DC").set(data3); final data4 = { "name": "Tokyo", "state": null, "country": "Japan", "capital": true, "population": 9000000, "regions": ["kanto", "honshu"] }; cities.doc("TOK").set(data4); final data5 = { "name": "Beijing", "state": null, "country": "China", "capital": true, "population": 21500000, "regions": ["jingjinji", "hebei"], }; cities.doc("BJ").set(data5); ``` -------------------------------- ### Get Firebase Installation Auth Token for Test Devices Source: https://firebase.google.com/docs/ab-testing/abtest-config Retrieve the Firebase installation auth token to assign specific A/B experiment variants to a test device for validation. The `forceRefresh` parameter ensures a new token is fetched. ```Swift do { let result = try await Installations.installations() .authTokenForcingRefresh(true) print("Installation auth token: \(result.authToken)") } catch { print("Error fetching token: \(error)") } ``` ```Objective-C [[FIRInstallations installations] authTokenForcingRefresh:true completion:^(FIRInstallationsAuthTokenResult *result, NSError *error) { if (error != nil) { NSLog(@"Error fetching Installation token %@", error); return; } NSLog(@"Installation auth token: %@", [result authToken]); }]; ``` ```Java FirebaseInstallations.getInstance().getToken(/* forceRefresh */true) .addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { if (task.isSuccessful() && task.getResult() != null) { Log.d("Installations", "Installation auth token: " + task.getResult().getToken()); } else { Log.e("Installations", "Unable to get Installation auth token"); } } }); MainActivity.java ``` ```Kotlin val forceRefresh = true FirebaseInstallations.getInstance().getToken(forceRefresh) .addOnCompleteListener { task -> if (task.isSuccessful) { Log.d("Installations", "Installation auth token: " + task.result?.token) } else { Log.e("Installations", "Unable to get Installation auth token") } } MainActivity.kt ``` ```Web import { getInstallations, getToken } from "firebase/installations"; const installations = getInstallations(app); const installationAuthToken = getToken(installations); ``` ```C++ firebase::InitResult init_result; auto* installations_object = firebase::installations::Installations::GetInstance( firebase::App::GetInstance(), &init_result); installations_object->GetToken().OnCompletion( [](const firebase::Future& future) { if (future.status() == kFutureStatusComplete && future.error() == firebase::installations::kErrorNone) { printf("Installations Auth Token %s\n", future.result()->c_str()); } }); ``` ```Unity Firebase.Installations.FirebaseInstallations.DefaultInstance.GetTokenAsync(forceRefresh: true).ContinueWith( task => { if (!(task.IsCanceled || task.IsFaulted) && task.IsCompleted) { UnityEngine.Debug.Log(System.String.Format("Installations token {0}", task.Result)); } }); ``` -------------------------------- ### Constructing LiveAudioConversationConfig with DSL Source: https://firebase.google.com/docs/reference/android/com/google/firebase/ai/type/LiveAudioConversationConfigKt Example demonstrating how to use the `liveAudioConversationConfig` helper method with a DSL-like syntax to configure a `LiveAudioConversationConfig`. ```kotlin liveAudioConversationConfig { functionCallHandler = ... initializationHandler = ... ... } ``` -------------------------------- ### Get All Documents in a Collection (Web v8 - Async/Await) Source: https://firebase.google.com/docs/firestore/enterprise/get-data-core This example shows how to get all documents from a Firestore collection using the Firebase Web v8 SDK with async/await. It fetches the snapshot and then iterates to log each document's ID and data. ```JavaScript const citiesRef = db.collection('cities'); const snapshot = await citiesRef.get(); snapshot.forEach(doc => { console.log(doc.id, '=>', doc.data()); }); ``` -------------------------------- ### Initialize Podfile for iOS Project Source: https://firebase.google.com/docs/admob/cpp/quick-start Navigate to your app's directory and run pod init to create a new Podfile for managing project dependencies. ```bash cd YOUR_APP_DIRECTORY pod init ``` -------------------------------- ### Get All Documents in a Collection (Web v8 - Promises) Source: https://firebase.google.com/docs/firestore/enterprise/get-data-core This example demonstrates how to get all documents from a Firestore collection using the Firebase Web v8 SDK with promises. It iterates through the query snapshot to log each document's ID and data. ```JavaScript db.collection("cities").get().then((querySnapshot) => { querySnapshot.forEach((doc) => { // doc.data() is never undefined for query doc snapshots console.log(doc.id, " => ", doc.data()); }); }); ``` -------------------------------- ### Get Fallback URL for AndroidParameters Source: https://firebase.google.com/docs/reference/android/com/google/firebase/dynamiclinks/DynamicLink.AndroidParameters.Builder Returns the fallback URL to open on Android if the app isn't installed. This method is deprecated. ```java publicĀ @NonNull UriĀ ~~getFallbackUrl~~() ``` -------------------------------- ### Get RecaptchaAppCheckProviderFactory Instance in Java Source: https://firebase.google.com/docs/reference/android/com/google/firebase/appcheck/recaptcha/RecaptchaAppCheckProviderFactory Use this static method to retrieve a singleton instance of `RecaptchaAppCheckProviderFactory` for installation into a `FirebaseAppCheck` instance. ```java public static @NonNull RecaptchaAppCheckProviderFactory getInstance() ``` -------------------------------- ### Create App Hosting Backend with Firebase CLI Source: https://firebase.google.com/docs/app-hosting/monorepos Use this command to initiate the backend setup flow for App Hosting. You will be prompted to specify your GitHub repository and the app's root directory within your monorepo. ```bash $ firebase apphosting:backends:create --project [project-name] i === Import a GitHub repository āœ” Connected with GitHub successfully ? Which GitHub repo do you want to deploy? gh-username/nx-monorepo ? Specify your app's root directory relative to your repository path/to/app ``` -------------------------------- ### ListSamlProviderConfigsAsync Source: https://firebase.google.com/docs/reference/admin/dotnet/class/firebase-admin/auth/abstract-firebase-auth Gets an async enumerable to iterate or page through SAML provider configurations starting from the specified page token. If the page token is null or unspecified, iteration starts from the first page. See Page Streaming for more details on how to use this API. ```APIDOC ## PagedAsyncEnumerable< AuthProviderConfigs< SamlProviderConfig >, SamlProviderConfig > ListSamlProviderConfigsAsync(ListProviderConfigsOptions options) ### Description Gets an async enumerable to iterate or page through SAML provider configurations starting from the specified page token. If the page token is null or unspecified, iteration starts from the first page. See Page Streaming for more details on how to use this API. ### Parameters - **options** (ListProviderConfigsOptions) - The options to control the starting point and page size. Pass null to list from the beginning with default settings. ### Returns A PagedAsyncEnumerable{AuthProviderConfigs, SamlProviderConfig} instance. ``` -------------------------------- ### Specify Emulators for `emulators:start` or `emulators:exec` Source: https://firebase.google.com/docs/emulator-suite/install_and_configure Use the `--only` flag to specify which emulators should be started when a `firebase.json` file is not present or when you only need a subset of emulators. ```bash --only functions,firestore ``` -------------------------------- ### ListTenantsAsync(ListTenantsOptions options) Source: https://firebase.google.com/docs/reference/admin/dotnet/class/firebase-admin/auth/multitenancy/tenant-manager Gets an async enumerable to iterate or page through tenants starting from the specified page token. If the page token is null or unspecified, iteration starts from the first page. See Page Streaming for more details on how to use this API. ```APIDOC ## ListTenantsAsync ### Description Gets an async enumerable to iterate or page through tenants starting from the specified page token. If the page token is null or unspecified, iteration starts from the first page. See Page Streaming for more details on how to use this API. ### Signature ``` PagedAsyncEnumerable< TenantsPage, Tenant > ListTenantsAsync( ListTenantsOptions options ) ``` ### Parameters - **options** (ListTenantsOptions) - The options to control the starting point and page size. Pass null to list from the beginning with default settings. ### Returns A PagedAsyncEnumerable{TenantsPage, Tenant} instance. ``` -------------------------------- ### Create New User with Multi-Factor Authentication (Node.js) Source: https://firebase.google.com/docs/auth/admin/manage-mfa-users This example demonstrates creating a new user with two pre-enrolled phone secondary factors. New users with secondary factors must have a verified email address and use a supported first factor. ```javascript admin.auth().createUser({ uid: '123456789', email: 'user@example.com', emailVerified: true, password: 'password', multiFactor: { enrolledFactors: [ // When creating users with phone second factors, the uid and // enrollmentTime should not be specified. These will be provisioned by // the Auth server. // Primary second factor. { phoneNumber: '+16505550001', displayName: 'Corp phone', factorId: 'phone' }, // Backup second factor. { phoneNumber: '+16505550002', displayName: 'Personal phone', factorId: 'phone' } ] } }) .then((userRecord) => { console.log(userRecord.multiFactor.enrolledFactors); }) .catch((error) => { console.log(error); }); ``` -------------------------------- ### Create Node.js Application Directory Source: https://firebase.google.com/docs/hosting/cloud-run Commands to create and enter the `helloworld-nodejs` directory for the Node.js sample application. ```bash mkdir helloworld-nodejs cd helloworld-nodejs ``` -------------------------------- ### Example Export Output URI Prefix Source: https://firebase.google.com/docs/firestore/manage-data/move-data Illustrates the format of the outputUriPrefix returned after starting a Cloud Firestore export operation, which includes a timestamp. ```text outputUriPrefix: gs://[SOURCE_BUCKET]/2019-03-05T20:58:23_56418 ``` -------------------------------- ### Configure Live API for Audio Transcription (Kotlin) Source: https://firebase.google.com/docs/ai-logic/live-api/configuration This Kotlin example shows how to set up the Live API model to receive transcriptions for both audio input and output, and how to handle them in a conversation. ```Kotlin // ... val liveModel = Firebase.ai(backend = GenerativeBackend.googleAI()).liveModel( modelName = "gemini-2.5-flash-native-audio-preview-12-2025", // Configure the model to return transcriptions of the audio input and output generationConfig = liveGenerationConfig { responseModality = ResponseModality.AUDIO inputAudioTranscription = AudioTranscriptionConfig() outputAudioTranscription = AudioTranscriptionConfig() } ) val liveSession = liveModel.connect() fun handleTranscription(input: Transcription?, output: Transcription?) { input?.text?.let { text -> // Handle transcription text of the audio input println("Input Transcription: $text") } output?.text?.let { text -> // Handle transcription text of the audio output println("Output Transcription: $text") } } liveSession.startAudioConversation(null, ::handleTranscription) // ... ``` -------------------------------- ### Register and Get Firebase Installation ID (JavaScript) Source: https://firebase.google.com/docs/cloud-messaging/js/client Use this snippet to initialize Firebase Messaging, register the app instance with a VAPID key, and set up a callback to receive the Firebase Installation ID (FID) upon registration or change. The FID should then be sent to your app server. ```javascript import { getMessaging, onRegistered, register } from "firebase/messaging"; const messaging = getMessaging(); // 1. Implement callback to receive the Firebase installation ID upon registration. // This is triggered every time a manual register() finishes, a FID change // is detected, or a pushsubscriptionchange event is fired. onRegistered(messaging, (installationId) => { console.log('Registered installation ID:', installationId); // Send the Firebase Installation ID to your app server and update the UI if needed. sendRegistrationToServer(installationId); }); // 2. You can also manually trigger registration (recommended on app startup) register(messaging, { vapidKey: '' }).then(() => { // Success! The Firebase Installation ID can be used to target messages to this app // instance and will be delivered asynchronously to your onRegistered() callback. }).catch((err) => { console.error('An error occurred while registering', err); }); ``` -------------------------------- ### gcloud CLI: Example - Clone Default Database Source: https://firebase.google.com/docs/firestore/manage-databases This example demonstrates cloning the default database from 'example-project' to 'example-dest-db' at a specific point in time using the gcloud CLI. ```shell gcloud firestore databases clone \ --source-database='projects/example-project/databases/(default)' \ --snapshot-time='2025-06-01T10:20:00.00Z' \ --destination-database='example-dest-db' ``` -------------------------------- ### Perform a count aggregation with Node.js Source: https://firebase.google.com/docs/firestore/query-data/aggregation-queries This example shows how to use getCountFromServer to get the number of documents matching a query in Node.js. It applies a where filter to the collection. ```Node.js const coll = collection(db, "cities"); const q = query(coll, where("state", "==", "CA")); const snapshot = await getCountFromServer(q); console.log('count: ', snapshot.data().count); count_aggregate_query.js ``` -------------------------------- ### Deploy Hosting Content to a Preview Channel Source: https://firebase.google.com/docs/cli/targets Use this command to deploy specific Hosting content and configuration to a preview channel for testing purposes. ```bash firebase hosting:channel:deploy CHANNEL_ID \ --only TARGET_NAME ``` -------------------------------- ### Start and Stop Audio Conversation Source: https://firebase.google.com/docs/ai-logic/live-api These snippets demonstrate how to initiate an audio conversation with the connected live session and how to stop it (JavaScript example includes stopping). ```APIDOC ### Start Audio Conversation (Java) Starts an audio conversation using the established live session. ```java Futures.addCallback(sessionFuture, new FutureCallback() { @Override public void onSuccess(LiveSession ses) { LiveSessionFutures session = LiveSessionFutures.from(ses); session.startAudioConversation(); } @Override public void onFailure(Throwable t) { // Handle exceptions } }, executor); ``` ``` ```APIDOC ### Start and Stop Audio Conversation (JavaScript) Starts an audio conversation with the live session and provides a controller to stop it. ```javascript const session = await liveModel.connect(); const audioConversationController = await startAudioConversation(session); // ... Later, to stop the audio conversation // await audioConversationController.stop() ``` ``` -------------------------------- ### Example `apphosting.staging.yaml` Configuration Source: https://firebase.google.com/docs/app-hosting/multiple-environments This configuration file specifies environment-specific overrides for a staging environment, including `runConfig` parameters and environment variables. ```yaml runConfig: cpu: 1 memoryMiB: 512 concurrency: 5 env: - variable: API_URL value: api.staging.service.com availability: - BUILD - variable: DATABASE_URL secret: secretStagingDatabaseURL ```