quickstart-js Documentation

Firebase Quickstart Samples for Web

5,369 stars TypeScript TypeScript 14 files ยท ~13,025 tokens
RAW Doc

Technical Documentation: firebase/quickstart-js

โ„น๏ธ Provenance: Multi-Tier Ingestion ยท CodeWiki Reference

Overview (`README.md`)

Firebase Quickstarts for Javascript

A collection of quickstart samples demonstrating the Firebase APIs using the Javascript SDK. For more information, see firebase.google.com/docs/web/setup.

Samples are organized into the following subdirectories and include README.md files with instructions for getting started:

  • Auth
    • Anonymous Auth
    • Custom Auth
    • Email and Password auth
    • Email Link auth
    • Phone Auth using a visible ReCaptcha
    • Phone Auth using an invisible ReCaptcha
    • Phone Auth using popup
    • Google Auth in a Chrome Extension
    • Facebook auth using Facebook login button
    • Facebook auth using Firebase popup
    • Facebook auth using Firebase redirect
    • Google auth using Google sign-in button
    • Google auth using Firebase popup
    • Google auth using Firebase redirect
    • Twitter auth using Firebase popup
    • Twitter auth using Firebase redirect
    • Microsoft auth using Firebase popup
    • Microsoft auth using Firebase redirect
    • GitHub auth using Firebase popup
    • GitHub auth using Firebase redirect
    • Multi-factor authentication with SMS(currently only available for Google Cloud Identity Platform projects)
  • Database
    • Simple Social Blogging app
  • Firestore
    • Simple Rating App
  • Functions
    • Send requests to a Functions server-side instance and get back results.
  • Storage
    • Upload a file to Firebase Storage and display its URL
  • Messaging
    • Send notifications

How to make contributions?

Please read and follow the steps in the CONTRIBUTING.md

License

See LICENSE

Build Status

Actions Status


Overview (`ai/README.md`)

Firebase AI SDK Quickstart

This directory contains samples for the Firebase AI SDK for Web.

Table of Contents

  1. Firebase AI Logic Feature Samples (ai-samples/): provides sample apps each demonstrating a single feature of the Firebase AI SDK for Web.

  2. Firebase AI Logic Sample App (ai-react-app/): demonstrates multiple features of the Firebase AI SDK for Web integrated into a web application built with React and TypeScript.


Overview (`auth/README.md`)

Firebase Auth Quickstarts

The Firebase Auth quickstart demonstrates several methods for signing in:

  • The Firebase email and password authentication quickstart demonstrates using a Firebase stored email & password to authenticate - you can both create and sign in a user.
  • The Firebase email link authentication quickstart demonstrates using an email address to sign-in without a password, via a link sent through email - you can both create and sign in a user.
  • The Firebase phone number authentication quickstart demonstrates using Firebase phone number authentication using three different techniques: with a visible ReCaptcha, an invisible ReCaptcha and a simplified popup flow (not recommended for production apps).
  • The Firebase Google Sign in quickstarts demonstrate using a Google account to authenticate to Firebase using three different techniques: with a popup, a redirect and an auth token.
  • The Firebase Facebook Login quickstarts demonstrate using a Facebook account to authenticate to Firebase using three different techniques: with a popup, a redirect and an auth token.
  • The Firebase Twitter Login quickstarts demonstrate using a Twitter account to authenticate to Firebase using two different techniques: with a popup and a redirect.
  • The Firebase Microsoft Login quickstarts demonstrate using a Microsoft account to authenticate to Firebase using two different techniques: with a popup and a redirect.
  • The Firebase GitHub Login quickstarts demonstrate using a GitHub account to authenticate to Firebase using two different techniques: with a popup and a redirect.
  • The multi-factor authentication quickstart demonstrates using email & password as the first factor and phone number as the second factor to authenticate - you can both enroll for the second factor and sign in with the second factor. Note: Multi-factor authentication with SMS is currently only available for Google Cloud Identity Platform projects.
  • The Firebase Anonymous auth quickstart demonstrates how to authenticate to Firebase anonymously.
  • The Firebase custom auth quickstart demonstrates how to authenticate to Firebase with a user who has been authenticated from your own pre-existing authentication system. This is done by generating a token in a specific format, which is signed using the private key from a service account downloaded from the Google Developer Console. This token can then be passed to your client application which uses it to authenticate to Firebase. We provide an example token generator for demonstration purposes. Note: Generating tokens in production should be done server side.

We also provide the code for a Chrome Extension showing how to setup and authorize Firebase in a Chrome extension.

Introduction

Read more about Firebase Auth

Getting Started

  1. Create a Firebase project on the Firebase Console. Copy your Firebase config object (from the "Add Firebase to your web app" dialog), and paste it in the config.ts file in the auth directory.
  2. Add a support email to your project in the settings page. Some auth methods won't work without this.
  3. Enable the authentication method you want to use by going to the Authentication section in the SIGN-IN METHOD tab - you don't need to enable custom auth.
    • For Custom Auth, generate a Service Account credentials in your Firebase Console > Project Settings > Service Accounts, and click on GENERATE NEW PRIVATE KEYS. You will need it in the example token generator.
    • For Facebook, Twitter and GitHub you will need to create an application as a developer on their respective developer platform, whitelist https://.firebaseapp.com/__/auth/handler for auth redirects and enable and setup the app's credentials in the Firebase Console > Authentication > SIGN-IN METHOD.
  4. You must have the Firebase CLI installed. If you don't have it install it with npm install firebase-tools and then configure it with firebase login.
  5. On the command line, cd into the quickstart-js/auth subdirectory.
  6. Run firebase use --add and select your Firebase project.

To run the sample app locally during development:

  1. Run npm install to install dependencies.
  2. Run firebase emulators:start to start the local Firebase emulators. Note: phone authentication required ReCaptcha verification which does not work with the Firebase emulators. These examples skip connecting to the emulators.
  3. Run npm run dev to serve the app locally using Vite
    This will start a server locally that serves index.html on http://localhost:5173/index.html.

Running the app using the Firebase CLI:

  1. Run npm install to install dependencies.
  2. Run npm run build to build the app using Vite.
  3. Run firebase emulators:start to start the local Firebase emulators. Note: phone authentication required ReCaptcha verification which does not work with the Firebase emulators. These examples skip connecting to the emulators.
  4. In your terminal output, you will see the "Hosting" URL. By default, it will be 127.0.0.1:5002, though it may be different for you.
  5. Navigate in your browser to the URL output by the firebase emulators:start command.

To deploy the sample app to production:

  1. Run firebase deploy.
    This will deploy the sample app to https://.firebaseapp.com.

Support

https://firebase.google.com/support/

License

ยฉ Google, 2016. Licensed under an Apache-2 license.


Overview (`database/README.md`)

Firebase Realtime Database Quickstart

The Firebase Database quickstart demonstrates how to connect to the Firebase Realtime Database and
to send and retrieve data through a simple social blogging app. It will interoperate with the iOS and
Android database quickstarts.

Introduction

Read more about Firebase Database

Getting Started

  1. Create your project on the Firebase Console. Copy your Firebase config object (from the "Add Firebase to your web app" dialog), and paste it in the config.ts file in the database directory.
  2. Enable the Google sign-in provider in the Authentication > SIGN-IN METHOD tab.
  3. You must have the Firebase CLI installed. If you don't have it install it with npm install firebase-tools and then configure it with firebase login.
  4. Run npm install to install the app's dependencies.
  5. On the command line run firebase use --add and select the Firebase project you have created.

To run the sample app locally during development:

  1. Run npm install to install dependencies.
  2. Run firebase emulators:start to start the local Firebase emulators.
  3. Run npm run dev to serve the app locally using Vite
    This will start a server locally that serves index.html on http://localhost:5173/index.html.

Running the app using the Firebase CLI:

  1. Run npm install to install dependencies.
  2. Run npm run build to build the app using Vite.
  3. Run firebase emulators:start to start the local Firebase emulators.
  4. In your terminal output, you will see the "Hosting" URL. By default, it will be 127.0.0.1:5002, though it may be different for you.
  5. Navigate in your browser to the URL output by the firebase emulators:start command.

To deploy the sample app to production:

  1. Run firebase deploy.
    This will deploy the sample app to https://.firebaseapp.com.

Support

License

ยฉ Google, 2016. Licensed under an Apache-2 license.


Overview (`dataconnect/README.md`)

Firebase Data Connect Quickstart

Introduction

This is a sample app for the preview version of Firebase DataConnect. This service is currently in Public Preview at no cost for a limited time.

Getting Started with Firebase DataConnect

Follow these steps to get up and running with Firebase DataConnect. For more detailed instructions, check out the official documentation.

1. Create a New Data Connect Service and Cloud SQL Instance

  1. Open Firebase Data Connect in your Firebase Console project and select Get Started.
  2. Create a new Data Connect service and a Cloud SQL instance. Ensure the Blaze plan is active. Find pricing details at Firebase Pricing.
  3. Choose your server region. If you plan to use vector search, select us-central1.
  4. Wait for the Cloud SQL instance to be provisioned. Once it's ready, you can manage it in the Cloud Console.

2. Set Up Firebase CLI

Ensure the Firebase CLI is installed and up to date:

bash
npm install firebase-tools

3. Cloning the Repository

This repository contains the quickstart to help you explore the functionalities of DataConnect.

  1. Clone this repository to your local machine.

  2. Navigate to the dataconnect folder and initialize your Firebase project:

    bash
    cd ./dataconnect

    (Optional): If you plan to use other Firebase features, run firebase init instead, and select both DataConnect options as well as any additional feature you want to use.

4. Installing VS Code Extension

  1. Install VS Code.
  2. Download and install the Firebase DataConnect extension.
  3. Open this quickstart in VS Code and log in to your Firebase account using the Firebase extension.
  4. In the Firebase DataConnect VSCode extension, click Start Emulators and confirm that the emulators are running in the terminal.

5. Populating the Database

  1. In VS Code, open dataconnect/movie_insert.gql. Ensure the emulators in the Firebase DataConnect extension are running.
  2. You should see a Run (local) button at the top of the file. Click this to insert mock movie data into your database.
  3. Check the DataConnect Execution terminal to confirm that the data was added successfully.

6. Running the App

  1. Navigate to the app folder and install dependencies:

    bash
    cd ./app
    npm install
  2. Start the app:

    bash
    npm run dev

7. Deployment

  1. Create a Web App in the Firebase Console and take note of your App ID.

  2. In the Firebase Console, click on Add App. You can ignore the SDK setup for now, but note the generated firebaseConfig object.

  3. Replace the firebaseConfig in app/src/lib/firebase.tsx:

    javascript
    const firebaseConfig = {
      apiKey: "API_KEY",
      authDomain: "PROJECT_ID.firebaseapp.com",
      projectId: "PROJECT_ID",
      storageBucket: "PROJECT_ID.appspot.com",
      messagingSenderId: "SENDER_ID",
      appId: "APP_ID"
    };
  4. Build the web app for hosting deployment:

    bash
    cd ./app
    npm run build
  5. Allow domains for Firebase Auth in your project console (e.g., http://127.0.0.1).

  6. In dataconnect/dataconnect.yaml, ensure that your instanceId, database, and serviceId match your project configuration:

    yaml
    specVersion: "v1alpha"
    serviceId: "your-service-id"
    location: "us-central1"
    schema:
      source: "./schema"
      datasource:
        postgresql:
          database: "your-database-id"
          cloudSql:
            instanceId: "your-instance-id"
    connectorDirs: ["./movie-connector"]
  7. Deploy your project:

    bash
    npm install firebase-tools
    firebase login --reauth
    firebase use --add
    firebase deploy --only dataconnect,hosting
  8. To compare schema changes, run:

    bash
    firebase dataconnect:sql:diff
  9. If the changes are acceptable, apply them with:

    bash
    firebase dataconnect:sql:migrate

License

ยฉ Google, 2024. Licensed under an Apache-2 license.


Overview (`firestore/README.md`)

Firestore Quickstart: Friendly Eats

Introduction

FriendlyEats is a restaurant recommendation app built on Firestore. It was built with the Angular Javascript framework, and can make use of Firebase's Local Emulator Suite (specifically, the Authentication, Storage, Functions, and Firestore emulators) so that the quickstart can be run without needing to create a project in the Firebase Console.

For more information about Firestore visit the Firestore docs.

For more information about the Firebase Emulator Suite visit the Emulator Suite docs

Prerequisites

Before following the steps to build and run this quickstart you will need:

  1. Node.Js Version 16.0 or higher
  2. Java JDK version 11 or higher.

Configure and run the app locally with emulators:

Follow these steps to setup and run the quickstart:

  1. Install the Angular CLI if you do not already have it installed on your machine:

    bash
    npm install @angular/cli
  2. Install the Firebase CLI if you do not have it installed on your machine:

    bash
    npm -g i firebase-tools
  3. Install and build all project dependencies

    bash
    npm install && (cd functions && npm install)

    Note: When modifying the contents of functions/src, be sure to run npm run build in the functions/ directory so that Typescript changes can be compiled and present in the next emulator run.

  4. Run and serve the project locally:

    bash
    npm start
  5. Open http://localhost:4200 in your browser and try out the app!

Configure and run the app with the Firebase Console:

Follow these steps to have a working version of the quickstart running with the Firebase console:

Note: In the original application (that runs on the emulators), there is a Firebase Function that updates the avgRating field of a restaurant whenever that restaurant recieves a review. While Authentication, Storage, and Firestore are offered as free services through the Firebase console, using Firebase Functions on the Firebase Console requires a billing plan. There is a free tier billing plan that allows up to 2 million free function calls per month, but enabling this plan requires presenting payment information to Firebase. The following instructions, therefore, exclude those steps needed to deploy and host functions on the Firebase Console. All application functionality, other than the auto-updating avgRating field for restaurants, is conserved.

  1. Create a new Firebase project in the Firebase Console

  2. On the project homepage, select Web under Get Started By Adding Firebase To Your App and follow prompts to create your app, making sure to copy the firebaseConfig object when presented.

  3. With the firebaseConfig copied, navigate to src/environments/environments.prod.ts and paste the contents of the object into the environment object:

  4. Back in the Firebase console, enable email and password authentication on your project by doing: Authentication > SIGN-IN METHOD > Email > Email/Password > SAVE

  5. In the Firebase console, enable Firestore on your project by clicking Create Database in the Cloud Firestore section of the console and answering all prompts.

  • When prompted, select "Start in Test Mode"
  1. Simmilarly, enable Cloud Storage on your project by clicking Get Started in the Storage section of the console and answering all prompts.
  • When prompted, select "Start in Test Mode"
  1. Set the CLI to use the project you created in Step 1:
bash
firebase use --add
  1. Serve your Angular app and see it connect to the Firebase Console by opening http://localhost:4200 in your browser!
bash
npm run production

Note: If you've opted to set up a billing plan and wish to deploy functions as well, replace the firebase deploy --only firestore on line 8 of package.json with firebase deploy.

  1. (Optional) Populate production Firestore with mock data

Now that the application is live on the Firebase console, you likely want to add some data to your production Firestore database so that you can see the application in action. Rather than manually adding restaurants and reviews, a convenice script is available to populate your production Firestore database. Run the following command (defined in the Firestore/ directory's package.json) to add mock data:

bash
npm run populate-production

Note: To ensure that the script runs as intended, make sure that you have correctly populated the environemnt.prod.ts file with your Firebase credentials.

Support

License

ยฉ Google, 2023. Licensed under an Apache-2 license.


Overview (`functions/README.md`)

Firebase HTTPS Callable functions Web Quickstart

The HTTPS Callable functions Web Quickstart demonstrates how to send requests to a server-side function and get a response back using the Firebase JS SDK. It interoperates with the iOS and Android database quickstarts.

Introduction

Read more about Cloud Functions for Firebase

Getting Started

  1. Create your project in the Firebase Console.
  2. Enable the Google sign-in provider in the Authentication > SIGN-IN METHOD tab.
  3. You must have the Firebase CLI installed. If you don't have it, install it with npm install firebase-tools and then configure it with firebase login.
  4. Clone this repository and open the functions directory: git clone https://github.com/firebase/quickstart-js; cd quickstart-js/functions
  5. Install cloud functions dependencies: npm --prefix functions install
  6. On the command line run firebase use --add and select the Firebase project you have created.
  7. On the command line run firebase deploy to deploy the application.
  8. On the command line run firebase open hosting:site to open the deployed web app.
  9. Sign in the Application using the Button.
  10. Write two numbers in the boxes and Click the "Add the Two Numbers" button.
    • You should be getting the result of the addition.
  11. Write a message in the Box below and Click the "Add Message" button.
    • The message is added below but if it contains bad words or SHOUTING!! it will be sanitized.

To run the sample app locally during development:

  1. Run npm install to install dependencies.
  2. Run npm --prefix functions run build to build the functions using Vite.
  3. Run firebase emulators:start to start the local Firebase emulators.
  4. Run npm run dev to serve the app locally using Vite
    This will start a server locally that serves index.html on http://localhost:5173/index.html.

Running the app using the Firebase CLI:

  1. Run npm install to install dependencies.
  2. Run npm run build to build the app using Vite.
  3. Run firebase emulators:start to start the local Firebase emulators.
  4. In your terminal output, you will see the "Hosting" URL. By default, it will be 127.0.0.1:5002, though it may be different for you.
  5. Navigate in your browser to the URL output by the firebase emulators:start command.

Support

License

ยฉ Google, 2018. Licensed under an Apache-2 license.


Overview (`messaging/README.md`)

Firebase Cloud Messaging Quickstart

The Firebase Cloud Messaging quickstart demonstrates how to:

  • Request permission to send app notifications to the user.
  • Receive FCM messages using the Firebase Cloud Messaging JavaScript SDK.

Introduction

Read more about Firebase Cloud Messaging

Getting Started

  1. Create your project in the Firebase Console by following Step 1: Create a Firebase Project
  2. Register a web app by following Step 2: Register your app with Firebase.
    1. You don't need to add Hosting right now, and you can skip the "Add Firebase SDK" step in the console's "Add Firebase to your web app" flow.
    2. Remember to click "Register App" or "Continue to console" at the bottom of the "Add Firebase to your web app" flow.
    3. Copy your Firebase config object (from the "Add Firebase to your web app" dialog), and paste it in the config.ts file in the messaging directory.
  3. Open Project and go to Project settings > Cloud Messaging and there in the Web configuration section click Generate key pair button.
  4. Copy public key and in the config.ts file replace <YOUR_PUBLIC_VAPID_KEY_HERE> with your key.
  5. You must have the Firebase CLI installed. If you don't have it install it with npm install firebase-tools and then configure it with firebase login.
  6. On the command line run firebase use --add and select the Firebase project you have created.

To run the sample app locally during development:

  1. Run npm install to install dependencies.
  2. Run firebase emulators:start to start the local Firebase emulators. Note: phone authentication required ReCaptcha verification which does not work with the Firebase emulators. These examples skip connecting to the emulators.
  3. Run npm run dev to serve the app locally using Vite.
    This will start a server locally that serves index.html on http://localhost:5173/index.html.
  4. Click REQUEST PERMISSION button to request permission for the app to send notifications to the browser and register.
  5. Use the registered Firebase Installation ID (FID) to send an HTTP request to FCM HTTP v1 API that delivers the message to the web application, inserting appropriate values for YOUR-PROJECT-ID, YOUR-ACCESS-TOKEN, and YOUR-FID.

Running the app using the Firebase CLI:

  1. Run npm install to install dependencies.
  2. Run npm run build to build the app using Vite.
  3. Run firebase emulators:start to start the local Firebase emulators. Note: phone authentication required ReCaptcha verification which does not work with the Firebase emulators. These examples skip connecting to the emulators.
  4. In your terminal output, you will see the "Hosting" URL. By default, it will be 127.0.0.1:5002, though it may be different for you.
  5. Navigate in your browser to the URL output by the firebase emulators:start command.
  6. Click REQUEST PERMISSION button to request permission for the app to send notifications to the browser.
  7. Use the registered Firebase Installation ID (FID) to send an HTTP request to FCM HTTP v1 API that delivers the message to the web application, inserting appropriate values for YOUR-PROJECT-ID, YOUR-ACCESS-TOKEN, and YOUR-FID.

To deploy the sample app to production:

  1. Run firebase deploy.
    This will deploy the sample app to https://.firebaseapp.com.

NOTE: If your payload has a notification object, onBackgroundMessage will not trigger. Read here for more information.

HTTP

text
POST /v1/projects/YOUR-PROJECT-ID/messages:send HTTP/1.1
Host: fcm.googleapis.com
Authorization: Bearer YOUR-ACCESS-TOKEN
Content-Type: application/json; UTF-8

{
  "message": {
    "fid": "YOUR-FID",
    "notification": {
      "title": "Portugal vs. Denmark",
      "body": "5 to 1"
    },
    "webpush": {
      "notification": {
        "icon": "/firebase-logo.png"
      }
    }
  }
}

Fetch

js
var projectId = 'YOUR-PROJECT-ID';
var accessToken = 'YOUR-ACCESS-TOKEN';
var fid = 'YOUR-FID';
var message = {
  fid: fid,
  notification: {
    title: 'Portugal vs. Denmark',
    body: '5 to 1',
  },
  webpush: {
    notification: {
      icon: '/firebase-logo.png',
    },
  },
};

fetch(
  'https://fcm.googleapis.com/v1/projects/' + projectId + '/messages:send',
  {
    method: 'POST',
    headers: {
      Authorization: 'Bearer ' + accessToken,
      'Content-Type': 'application/json; UTF-8',
    },
    body: JSON.stringify({
      message: message,
    }),
  },
)
  .then(function (response) {
    return response.json();
  })
  .then(function (data) {
    console.log(data);
  })
  .catch(function (error) {
    console.error(error);
  });

cURL

text
curl -X POST -H "Authorization: Bearer YOUR-ACCESS-TOKEN" -H "Content-Type: application/json; UTF-8" -d '{
  "message": {
    "fid": "YOUR-FID",
    "notification": {
      "title": "Portugal vs. Denmark",
      "body": "5 to 1"
    },
    "webpush": {
      "notification": {
        "icon": "/firebase-logo.png"
      }
    }
  }
}' "https://fcm.googleapis.com/v1/projects/YOUR-PROJECT-ID/messages:send"

App focus

When the app has the browser focus, the received message is handled through
the onMessage callback in main.ts. When the app does not have browser
focus then the onBackgroundMessage callback in firebase-messaging-sw.js
is where the received message is handled.

The browser gives your app focus when both:

  1. Your app is running in the currently selected browser tab.
  2. The browser tab's window currently has focus, as defined by the operating system.

Support

https://firebase.google.com/support/

License

ยฉ Google, 2016. Licensed under an Apache-2 license.


Overview (`remote-config/README.md`)

Firebase Remote Config Quickstart

The Firebase Remote Config Web quickstart app demonstrates using Remote
Config to define user-facing text in a web app.

Introduction

This is a simple example of using Remote Config to override in-app default
values by defining server-side parameter values in the Firebase console. This
example demonstrates a small subset of the capilities of Firebase Remote
Config. To learn more about how you can use Firebase Remote Config in your app,
see
the Firebase Remote Config introduction.

Getting started

  1. Follow step 1 and 2 here to register a web app with your Firebase project. Copy your Firebase config object (from the "Add Firebase to your web app" dialog), and paste it in the config.ts file in the remote-config directory.
  2. Set up Remote Config for your Firebase project:
    1. In the Firebase console, open your project
    2. Select Remote Config from the menu to view the Remote Config dashboard
    3. Define a parameter with key welcome_message and default value Hello World
    4. Click "Add parameter", and then click "Publish changes"
  3. You must have the Firebase CLI installed. If you don't have it install it with npm install firebase-tools and then configure it with firebase login.
  4. On the command line run firebase use --add and select the Firebase project you have created

To run the sample app locally during development:

  1. Run npm install to install dependencies.
  2. Run firebase emulators:start to start the local Firebase emulators. Note: phone authentication required ReCaptcha verification which does not work with the Firebase emulators. These examples skip connecting to the emulators.
  3. Run npm run dev to serve the app locally using Vite
    This will start a server locally that serves index.html on http://localhost:5173/index.html.
  4. Click REQUEST PERMISSION button to request permission for the app to send notifications to the browser.
  5. Use the generated Instance ID token (IID Token) to send an HTTP request to FCM that delivers the message to the web application, inserting appropriate values for YOUR-SERVER-KEY and YOUR-IID-TOKEN.
  6. Change the parameter value in the Firebase Console (the value of
    welcome_message), and then click "Publish changes"
  7. Tap Fetch Remote Welcome in the app to fetch new parameter values and see
    the resulting change in the app.

Running the app using the Firebase CLI:

  1. Run npm install to install dependencies.
  2. Run npm run build to build the app using Vite.
  3. Run firebase emulators:start to start the local Firebase emulators. Note: phone authentication required ReCaptcha verification which does not work with the Firebase emulators. These examples skip connecting to the emulators.
  4. In your terminal output, you will see the "Hosting" URL. By default, it will be 127.0.0.1:5002, though it may be different for you.
  5. Navigate in your browser to the URL output by the firebase emulators:start command.
  6. Click REQUEST PERMISSION button to request permission for the app to send notifications to the browser.
  7. Use the generated Instance ID token (IID Token) to send an HTTP request to FCM that delivers the message to the web application, inserting appropriate values for YOUR-SERVER-KEY and YOUR-IID-TOKEN.
  8. Change the parameter value in the Firebase Console (the value of
    welcome_message), and then click "Publish changes"
  9. Tap Fetch Remote Welcome in the app to fetch new parameter values and see
    the resulting change in the app.

To deploy the sample app to production:

  1. Run firebase deploy.
    This will deploy the sample app to https://.firebaseapp.com.

Best practices

This section provides some additional information about how the quickstart
example sets in-app default parameter values and fetches values from the Remote
Config service

In-app default parameter values

In-app default values are set using a JSON object using the setDefaults method.
Then, you can override only those values that you need to change from the
Firebase console or the REST API. This lets you use Remote Config for any default
value that you might want to override in the future, without the need to set all of
those values in the Firebase console.

Fetch values from the Remote Config service

When an app calls fetch, locally stored parameter values are used unless the
minimum fetch interval is reached. The minimal fetch interval is determined by:

  1. The parameter passed to fetch(long minFetchInterval).
  2. The minimum fetch interval set in Remote Config settings.
  3. The default minimum fetch interval, 12 hours.

Fetched values are immediately activated when retrieved using fetchAndActivate.
In the quickstart sample app, you call fetchAndActivate from the UI by tapping
Fetch Remote Welcome.

To control when fetched values are activated and available to your app use fetch.
The values are locally stored, but not immediately activated. To activate fetched
values so that they take effect, call the activate method.

You can also create a Remote Config Setting to enable "developer mode". By
using a small (even 0) value for minimumFetchIntervalInSeconds, you can make many
more requests per hour, so you can test your app with different Remote Config
parameter values during development.

Support

License

Copyright 2019 Google, Inc.

Licensed to the Apache Software Foundation (ASF) under one or more contributor
license agreements. See the NOTICE file distributed with this work for
additional information regarding copyright ownership. The ASF licenses this
file to you under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy of
the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License.


Overview (`storage/README.md`)

Firebase SDK for Cloud Storage Quickstart

The Firebase SDK for Cloud Storage quickstart demonstrates how to connect to Cloud Storage, store data, and retrieve a download URL from a web client.

Introduction

Read more about Firebase SDK for Cloud Storage

Getting Started

  1. Create your project on the Firebase Console.
  2. Enable the Anonymous sign-in provider in the Authentication > SIGN-IN METHOD tab.
  3. You must have the Firebase CLI installed. If you don't have it install it with npm install firebase-tools and then configure it with firebase login.
  4. On the command line run firebase use --add and select the Firebase project you have created.
  5. On the command line run firebase serve using the Firebase CLI tool to launch a local server.

Support

License

ยฉ Google, 2016. Licensed under an Apache-2 license.


Overview (`ai/ai-react-app/README.md`)

Firebase AI Logic Sample App

This sample application demonstrates features of the Firebase AI SDK for Web (firebase/ai), integrated into a web application built with React and TypeScript.

For more information about the Firebase AI SDK, see the Firebase AI Logic Docs.

Setup Instructions

  1. Use the guided workflow in the Firebase AI Logic page of the Firebase Console to setup your project (including enabling the required APIs for your chosen Gemini API provider), then register your app with your Firebase project.

  2. Update src/config/firebase-config.ts with your Firebase configuration.

  3. Install dependencies:

    bash
    yarn
  4. Start the development server:

    bash
    yarn dev

Support

License

ยฉ Google, 2025. Licensed under an Apache-2


Overview (`ai/ai-samples/README.md`)

Firebase AI Samples

A modular migration of the Firebase AI logic, demonstrating different capabilities:

Samples

You can open this sample as a Node/React project and run it in your local browser. When doing so, you need to add this sample app to a Firebase project on the Firebase console. You can add multiple sample apps to the same Firebase project; no need to create separate projects for each app.

This repository demonstrates the following capabilities:

  • Text Generation
  • Chat
  • Multimodal
  • Structured Output
  • Function Calling
  • Automatic Function Calling
  • Image Generation
  • Video Analysis
  • Grounding with Google Search
  • Server Prompt Templates

Setup & Configuration

To connect this sample app to your Firebase project, register a new Web App in your Firebase Console to generate your Firebase configuration object.

  1. Navigate to this directory and install dependencies:

    bash
    npm install
  2. Add your Firebase config

Go to console.firebase.google.com and follow the Firebase AI Logic guided setup to enable the API and choose your gemini API provider.
Copy the example config file and fill in your project values. Open src/config/firebase-config.ts and replace the placeholder values with your firebase project config (found in Project Settings -> your apps)

  1. Running the samples

For a full app experience to browse all features:

bash
npm run dev

To run individual features in isolated mode, run the single feature directly without the app shell using one of these scripts:

bash
npm run dev:text          # Text Generation
npm run dev:chat          # Chat
npm run dev:multimodal    # Multimodal
npm run dev:structured    # Structured Output
npm run dev:function      # Function Calling
npm run dev:auto-function # Automatic Function Calling
npm run dev:image         # Image Generation
npm run dev:video         # Video Analysis
npm run dev:grounding     # Grounding with Google Search
# Note: Server Prompt Templates requires template setup in the Firebase Console first.
# See src/features/server-prompt-templates/README.md for setup instructions before running:
npm run dev:template      # Server Prompt Templates

After running any of the above commands, open your browser to http://localhost:*** (provided in the console)

Copy service.ts for platform agnostic use

All AI logic is decoupled from the React UI. If you want to use these features in your own project, navigate to any src/features/*/service.ts file. These files are framework-agnostic and can be safely copy-pasted into any JavaScript or TypeScript web project.

App Check

App check protects your API Key from unauthorized use. It is not required to run the samples locally but highly recommended before deploying to production.

Debug token:
firebaseAIService.ts includes App Check initialization for local development. To enable it:

  1. Set VITE_APPCHECK_DEBUG_TOKEN=true in your .env.local file
  2. On the first run, a debug token will be printed in the browser console.
  3. Copy that token and register it in the Firebase Console under
    App Check -> Apps -> your apps -> Debug Token

Production setup:
For production, use reCAPTCHA v3 as the App Check provider:

  1. Go to the Firebase Console -> App Check -> Register your app
  2. Choose reCaptcha v3 and follow the setup steps
  3. Add your reCaptcha site key to firebase-config.ts

See the App Check Docs for full instructions.


Overview (`auth/chromextension/README.md`)

Firebase Auth w/ Google Sign-In in Chrome Extensions

This sample demonstrates how to authorize a user with Firebase in a Chrome extension using Google Sign-In and setup the Chrome extension to allow the use of the Realtime Database and Firebase Storage.

Introduction

Setting up this sample

Creating a dummy Chrome extension (how to obtain a Chrome App ID and Public Key)

Setting up authentication in Chrome extensions is a bit of a chicken vs. egg problem. You need the Public Key and Chrome App ID to configure your manifest.json file, but you have to publish that to the Chrome Store to get the values. So we will publish a dummy app in order to obtain these.

Create a new directory and add a manifest.json file similar to the following:

text
{
  "manifest_version": 2,
  "name": "Firebase Auth in Chrome Extension Sample",
  "description": "This sample shows how to authorize Firebase in a Chrome extension using a Google account.",
  "version": "0.1",
  "permissions": [
    "identity"
  ]
}

Zip the directory:

text
cd ..
zip -r <chrome ext name>.zip <directory name>

Upload the dummy extension to the app store by going to the Chrome App Developer Dashboard and clicking Add a New Item. For more reading on publishing to the Chrome Web Store, go here.

Of course if you already own an extension and would like to add Firebase to it, skip the steps above.

Once the extension is uploaded and visible under Your Listings, click the more info link to the right. Copy down both the Item ID (e.g. kjdohecpbfnjbinmakjcmpgpbbhhijgf) and Public Key (e.g. MIIBIjANBgkqhkiG9w0B...long string of text...unbQIDAQAB). You will need both of these below.

Creating an OAuth Client

  • Create a new OAuth Client ID in your project's Developers Console (Click this link and select your Firebase project).
  • Select Chrome App and enter your Chrome Extension/App ID (the Item ID obtained above).
  • Note the Client ID (e.g. 7159....j00.apps.googleusercontent.com) as you will need this below.

Configuring your Firebase Project

  • Create or select a Firebase project at Firebase Console.
  • Enable the Google authentication method in the Auth section > SIGN IN METHOD tab.
  • Add the Client ID you created to the whitelist using the Whitelist client IDs from external projects (optional)
  • Edit the credential.js and background.js and enter your project's identifiers you get from the Firebase Console Overview > Add Firebase to your web app.
  • Edit the manifest.json
    • Enter your OAuth Client ID and your extension's Public Key.
    • Remove all comment lines (starting with //) in the manifest.json file before deploying your extension online.
  • Install the Extension in your browser and click on the extension's icon once installed. The first time your users will install the extension they will have to authorize Firebase using the login button.

Using Firebase in your own extension

The keys to using Firebase in a Chrome extension are:

  • Because of Chrome Extensions' Content Security Policy you need to avoid inline JavaScript in your HTML pages so you need to add the Firebase initialisation snippet in your JS file instead of inside the HTML file as we typically instruct. The Firebase initialisation snippet looks like this:
javascript
// Initialize Firebase
var config = {
   apiKey: "<qwertyuiopasdfghjklzxcvbnm>",
   databaseURL: "https://<my-app-id>.firebaseio.com",
   storageBucket: "<my-app-id>.appspot.com"
};
firebase.initializeApp(config);
  • Create a Google Client ID that's authorized for your Chrome extension and whitelist it in your Firebase project:
    • Create a new OAuth Client ID in your project's Developers Console, Select Chrome App and enter your Chrome Extension/App ID.
    • In your project's Firebase Console, enable the Google authentication method in the Auth section > SIGN IN METHOD tab.
    • Add the Client ID you created to the whitelist using the Whitelist client IDs from external projects (optional)
  • Use the chrome.identity API to get a Google OAuth token as described in https://developer.chrome.com/apps/app_identity and then use this token to authorize Firebase using Auth.signInWithCredential():
javascript
var credential = firebase.auth.GoogleAuthProvider.credential(null, token);
firebase.auth().signInWithCredential(credential);
  • Add the following content security policy to your manifest.json to allow importing the Firebase SDK and accessing the Realtime Database as well as Firebase Storage:
javascript
"content_security_policy":"script-src 'self' https://www.gstatic.com/ https://*.firebaseio.com https://www.googleapis.com; object-src 'self'"

Support

https://firebase.google.com/support/

License

ยฉ Google, 2016. Licensed under an Apache-2 license.


Overview (`ai/ai-samples/src/features/server-prompt-templates/README.md`)

Firebase AI Logic: Server Prompt Templates Sample

This quickstart demonstrates how to fetch and execute centrally managed prompt templates stored in the Firebase Console using the Firebase AI Logic SDK.

Why Server Prompt Templates?

  • No deployment updates: Change prompts, tune system instructions, or switch underlying models directly in the Firebase Console without having to release a new app version.
  • Security: Protect against exposing your prompt client-side.

1. Firebase Console Setup

Before running this sample, create and lock the template in your Firebase project:

  1. Open the Firebase Console and select your project.
  2. In the left navigation, navigate to AI Logic > Prompt Templates.
  3. Click Create Template. Note that these starter templates provide the format and syntax for some common use cases and this tutorial assumes you've selected the Input + System Instructions option. Once you clicked that, configure the following:
    • Template ID: invoice-generator
    • Model: gemini-3.5-flash-lite (or any available Gemini model)
  4. In the Prompt Content / System Instructions text area, paste the following prompt:
    text
    {{role "system"}}
     All output must be a clearly structured invoice document.
     Use a tabular or clearly delineated list format for line items.
    
     {{role "user"}}
     Create an example customer invoice for a customer named {{customerName}}.
  5. Click Save.
  6. Important: While client applications can execute both unlocked (draft) and locked templates during development, you should always Lock your template before deploying to production. Locking freezes the prompt configuration, ensuring that subsequent console edits do not accidentally change your production app's behavior.

2. Running the Sample Locally

Run the sample inside the full app shell:

bash
npm run dev

Or run this feature directly in isolated mode:

bash
npm run dev:template

Open your browser to the local URL (e.g., http://localhost:*** provided in the console).


3. Possible Troubleshooting & Failure Surfaces

Issue Cause Resolution
NOT_FOUND / 404 Template ID mismatch or template doesn't exist in the active Firebase project Verify that the template ID in your code is exactly invoice-generator and that you are initialized in the correct Firebase Project
Missing Variable output Variable names in client code don't match console Ensure the keys passed to templateVariables match the {{variable}} placeholders in your prompt template.
PERMISSION_DENIED Firebase AI Logic API not enabled or App Check blocked Follow the Firebase AI Logic guided setup in the console and ensure your API key / App Check tokens are valid.

--- METRICS ---