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
Overview (`ai/README.md`)
Firebase AI SDK Quickstart
This directory contains samples for the Firebase AI SDK for Web.
Table of Contents
Firebase AI Logic Feature Samples (
ai-samples/): provides sample apps each demonstrating a single feature of the Firebase AI SDK for Web.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
Getting Started
- 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.tsfile in the auth directory. - Add a support email to your project in the settings page. Some auth methods won't work without this.
- 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/handlerfor auth redirects and enable and setup the app's credentials in the Firebase Console > Authentication > SIGN-IN METHOD.
- You must have the Firebase CLI installed. If you don't have it install it with
npm install firebase-toolsand then configure it withfirebase login. - On the command line,
cdinto thequickstart-js/authsubdirectory. - Run
firebase use --addand select your Firebase project.
To run the sample app locally during development:
- Run
npm installto install dependencies. - Run
firebase emulators:startto 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. - Run
npm run devto serve the app locally using Vite
This will start a server locally that servesindex.htmlonhttp://localhost:5173/index.html.
Running the app using the Firebase CLI:
- Run
npm installto install dependencies. - Run
npm run buildto build the app using Vite. - Run
firebase emulators:startto 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. - 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. - Navigate in your browser to the URL output by the
firebase emulators:startcommand.
To deploy the sample app to production:
- Run
firebase deploy.
This will deploy the sample app tohttps://.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
- 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.tsfile in the database directory. - Enable the Google sign-in provider in the Authentication > SIGN-IN METHOD tab.
- You must have the Firebase CLI installed. If you don't have it install it with
npm install firebase-toolsand then configure it withfirebase login. - Run
npm installto install the app's dependencies. - On the command line run
firebase use --addand select the Firebase project you have created.
To run the sample app locally during development:
- Run
npm installto install dependencies. - Run
firebase emulators:startto start the local Firebase emulators. - Run
npm run devto serve the app locally using Vite
This will start a server locally that servesindex.htmlonhttp://localhost:5173/index.html.
Running the app using the Firebase CLI:
- Run
npm installto install dependencies. - Run
npm run buildto build the app using Vite. - Run
firebase emulators:startto start the local Firebase emulators. - 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. - Navigate in your browser to the URL output by the
firebase emulators:startcommand.
To deploy the sample app to production:
- Run
firebase deploy.
This will deploy the sample app tohttps://.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
- Open Firebase Data Connect in your Firebase Console project and select Get Started.
- Create a new Data Connect service and a Cloud SQL instance. Ensure the Blaze plan is active. Find pricing details at Firebase Pricing.
- Choose your server region. If you plan to use vector search, select
us-central1. - 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:
npm install firebase-tools3. Cloning the Repository
This repository contains the quickstart to help you explore the functionalities of DataConnect.
Clone this repository to your local machine.
Navigate to the
dataconnectfolder and initialize your Firebase project:bashcd ./dataconnect(Optional): If you plan to use other Firebase features, run
firebase initinstead, and select both DataConnect options as well as any additional feature you want to use.
4. Installing VS Code Extension
- Install VS Code.
- Download and install the Firebase DataConnect extension.
- Open this quickstart in VS Code and log in to your Firebase account using the Firebase extension.
- In the Firebase DataConnect VSCode extension, click Start Emulators and confirm that the emulators are running in the terminal.
5. Populating the Database
- In VS Code, open
dataconnect/movie_insert.gql. Ensure the emulators in the Firebase DataConnect extension are running. - You should see a Run (local) button at the top of the file. Click this to insert mock movie data into your database.
- Check the DataConnect Execution terminal to confirm that the data was added successfully.
6. Running the App
Navigate to the
appfolder and install dependencies:bashcd ./app npm installStart the app:
bashnpm run dev
7. Deployment
Create a Web App in the Firebase Console and take note of your App ID.
In the Firebase Console, click on Add App. You can ignore the SDK setup for now, but note the generated
firebaseConfigobject.Replace the
firebaseConfiginapp/src/lib/firebase.tsx:javascriptconst firebaseConfig = { apiKey: "API_KEY", authDomain: "PROJECT_ID.firebaseapp.com", projectId: "PROJECT_ID", storageBucket: "PROJECT_ID.appspot.com", messagingSenderId: "SENDER_ID", appId: "APP_ID" };Build the web app for hosting deployment:
bashcd ./app npm run buildAllow domains for Firebase Auth in your project console (e.g.,
http://127.0.0.1).In
dataconnect/dataconnect.yaml, ensure that yourinstanceId,database, andserviceIdmatch your project configuration:yamlspecVersion: "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"]Deploy your project:
bashnpm install firebase-tools firebase login --reauth firebase use --add firebase deploy --only dataconnect,hostingTo compare schema changes, run:
bashfirebase dataconnect:sql:diffIf the changes are acceptable, apply them with:
bashfirebase 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:
Configure and run the app locally with emulators:
Follow these steps to setup and run the quickstart:
Install the Angular CLI if you do not already have it installed on your machine:
bashnpm install @angular/cliInstall the Firebase CLI if you do not have it installed on your machine:
bashnpm -g i firebase-toolsInstall and build all project dependencies
bashnpm install && (cd functions && npm install)Note: When modifying the contents of
functions/src, be sure to runnpm run buildin thefunctions/directory so that Typescript changes can be compiled and present in the next emulator run.Run and serve the project locally:
bashnpm startOpen 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
avgRatingfield 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-updatingavgRatingfield for restaurants, is conserved.
Create a new Firebase project in the Firebase Console
On the project homepage, select
WebunderGet Started By Adding Firebase To Your Appand follow prompts to create your app, making sure to copy thefirebaseConfigobject when presented.With the
firebaseConfigcopied, navigate tosrc/environments/environments.prod.tsand paste the contents of the object into theenvironmentobject:Back in the Firebase console, enable email and password authentication on your project by doing: Authentication > SIGN-IN METHOD > Email > Email/Password > SAVE
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"
- 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"
- Set the CLI to use the project you created in Step 1:
firebase use --add- Serve your Angular app and see it connect to the Firebase Console by opening http://localhost:4200 in your browser!
npm run productionNote: If you've opted to set up a billing plan and wish to deploy functions as well, replace the
firebase deploy --only firestoreon line 8 ofpackage.jsonwithfirebase deploy.
- (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:
npm run populate-productionNote: To ensure that the script runs as intended, make sure that you have correctly populated the
environemnt.prod.tsfile 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
- Create your project in the Firebase Console.
- Enable the Google sign-in provider in the Authentication > SIGN-IN METHOD tab.
- You must have the Firebase CLI installed. If you don't have it, install it with
npm install firebase-toolsand then configure it withfirebase login. - Clone this repository and open the functions directory:
git clone https://github.com/firebase/quickstart-js; cd quickstart-js/functions - Install cloud functions dependencies:
npm --prefix functions install - On the command line run
firebase use --addand select the Firebase project you have created. - On the command line run
firebase deployto deploy the application. - On the command line run
firebase open hosting:siteto open the deployed web app. - Sign in the Application using the Button.
- Write two numbers in the boxes and Click the "Add the Two Numbers" button.
- You should be getting the result of the addition.
- 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:
- Run
npm installto install dependencies. - Run
npm --prefix functions run buildto build the functions using Vite. - Run
firebase emulators:startto start the local Firebase emulators. - Run
npm run devto serve the app locally using Vite
This will start a server locally that servesindex.htmlonhttp://localhost:5173/index.html.
Running the app using the Firebase CLI:
- Run
npm installto install dependencies. - Run
npm run buildto build the app using Vite. - Run
firebase emulators:startto start the local Firebase emulators. - 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. - Navigate in your browser to the URL output by the
firebase emulators:startcommand.
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
- Create your project in the Firebase Console by following Step 1: Create a Firebase Project
- Register a web app by following Step 2: Register your app with Firebase.
- 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.
- Remember to click "Register App" or "Continue to console" at the bottom of the "Add Firebase to your web app" flow.
- Copy your Firebase config object (from the "Add Firebase to your web app" dialog), and paste it in the
config.tsfile in the messaging directory.
- Open Project and go to Project settings > Cloud Messaging and there in the Web configuration section click Generate key pair button.
- Copy public key and in the
config.tsfile replace<YOUR_PUBLIC_VAPID_KEY_HERE>with your key. - You must have the Firebase CLI installed. If you don't have it install it with
npm install firebase-toolsand then configure it withfirebase login. - On the command line run
firebase use --addand select the Firebase project you have created.
To run the sample app locally during development:
- Run
npm installto install dependencies. - Run
firebase emulators:startto 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. - Run
npm run devto serve the app locally using Vite.
This will start a server locally that servesindex.htmlonhttp://localhost:5173/index.html. - Click REQUEST PERMISSION button to request permission for the app to send notifications to the browser and register.
- 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, andYOUR-FID.
Running the app using the Firebase CLI:
- Run
npm installto install dependencies. - Run
npm run buildto build the app using Vite. - Run
firebase emulators:startto 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. - 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. - Navigate in your browser to the URL output by the
firebase emulators:startcommand. - Click REQUEST PERMISSION button to request permission for the app to send notifications to the browser.
- 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, andYOUR-FID.
To deploy the sample app to production:
- Run
firebase deploy.
This will deploy the sample app tohttps://.firebaseapp.com.
NOTE: If your payload has a notification object, onBackgroundMessage will not trigger. Read here for more information.
HTTP
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
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
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:
- Your app is running in the currently selected browser tab.
- 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
- 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.tsfile in the remote-config directory. - Set up Remote Config for your Firebase project:
- In the Firebase console, open your project
- Select Remote Config from the menu to view the Remote Config dashboard
- Define a parameter with key
welcome_messageand default valueHello World - Click "Add parameter", and then click "Publish changes"
- You must have the Firebase CLI installed. If you don't have it install it with
npm install firebase-toolsand then configure it withfirebase login. - On the command line run
firebase use --addand select the Firebase project you have created
To run the sample app locally during development:
- Run
npm installto install dependencies. - Run
firebase emulators:startto 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. - Run
npm run devto serve the app locally using Vite
This will start a server locally that servesindex.htmlonhttp://localhost:5173/index.html. - Click REQUEST PERMISSION button to request permission for the app to send notifications to the browser.
- 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-KEYandYOUR-IID-TOKEN. - Change the parameter value in the Firebase Console (the value of
welcome_message), and then click "Publish changes" - 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:
- Run
npm installto install dependencies. - Run
npm run buildto build the app using Vite. - Run
firebase emulators:startto 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. - 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. - Navigate in your browser to the URL output by the
firebase emulators:startcommand. - Click REQUEST PERMISSION button to request permission for the app to send notifications to the browser.
- 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-KEYandYOUR-IID-TOKEN. - Change the parameter value in the Firebase Console (the value of
welcome_message), and then click "Publish changes" - 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:
- Run
firebase deploy.
This will deploy the sample app tohttps://.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:
- The parameter passed to
fetch(long minFetchInterval). - The minimum fetch interval set in Remote Config settings.
- 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.
- To learn more about fetching data from remote config, see Firebase Remote Config
loading strategies. - To learn about parameters and conditions that you can use to change the
behavior and appearance of your app for segments of your userbase, see
Remote Config Parameters and Conditions.
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
- Create your project on the Firebase Console.
- Enable the Anonymous sign-in provider in the Authentication > SIGN-IN METHOD tab.
- You must have the Firebase CLI installed. If you don't have it install it with
npm install firebase-toolsand then configure it withfirebase login. - On the command line run
firebase use --addand select the Firebase project you have created. - On the command line run
firebase serveusing 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
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.
Update
src/config/firebase-config.tswith your Firebase configuration.Install dependencies:
bashyarnStart the development server:
bashyarn 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.
Navigate to this directory and install dependencies:
bashnpm installAdd 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)
- Running the samples
For a full app experience to browse all features:
npm run devTo run individual features in isolated mode, run the single feature directly without the app shell using one of these scripts:
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 TemplatesAfter 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:
- Set VITE_APPCHECK_DEBUG_TOKEN=true in your .env.local file
- On the first run, a debug token will be printed in the browser console.
- 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:
- Go to the Firebase Console -> App Check -> Register your app
- Choose reCaptcha v3 and follow the setup steps
- 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:
{
"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:
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 IDobtained 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.jsandbackground.jsand 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 themanifest.jsonfile 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:
// 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():
var credential = firebase.auth.GoogleAuthProvider.credential(null, token);
firebase.auth().signInWithCredential(credential);- Add the following content security policy to your
manifest.jsonto allow importing the Firebase SDK and accessing the Realtime Database as well as Firebase Storage:
"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:
- Open the Firebase Console and select your project.
- In the left navigation, navigate to AI Logic > Prompt Templates.
- 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 Instructionsoption. Once you clicked that, configure the following:- Template ID:
invoice-generator - Model:
gemini-3.5-flash-lite(or any available Gemini model)
- Template ID:
- 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}}. - Click Save.
- 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:
npm run devOr run this feature directly in isolated mode:
npm run dev:templateOpen 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 ---
- Files Extracted: 14
- Estimated Token Budget: ~12941 tokens
- Canonical Reference: https://codewiki.google/github.com/firebase/quickstart-js