# Firebase AI Logic on Web (JavaScript) ## Installation The library is part of the standard Firebase Web SDK: ```bash npm install firebase@latest ``` ## Initialization Pattern You must initialize the ai-logic service after the main Firebase App. ```JavaScript import { initializeApp } from "firebase/app"; import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai"; // If running in Firebase App Hosting, you can skip Firebase Config and instead use: // const app = initializeApp(); const firebaseConfig = { // ... your firebase config }; const app = initializeApp(firebaseConfig); // Initialize the AI Logic service (defaults to Gemini Developer API) // Pass useLimitedUseAppCheckTokens: true to enable replay protection: const ai = getAI(app, { backend: new GoogleAIBackend(), useLimitedUseAppCheckTokens: true, }); const generationConfig = { candidateCount: 1, maxOutputTokens: 2048, stopSequences: [], temperature: 0.7, // Balanced: creative but focused topP: 0.95, // Standard: allows a wide range of probable tokens topK: 40, // Standard: considers the top 40 tokens }; // Specify the config as part of creating the `GenerativeModel` instance // [AGENT] Replace "" with the latest model from https://firebase.google.com/docs/ai-logic/models.md.txt (do NOT use Gemini 1.x or 2.x models like gemini-1.5-flash, gemini-2.0-flash, or gemini-2.5-flash) const model = getGenerativeModel(ai, { model: "", generationConfig }); ``` ### App Check Replay Protection Generative and preview models enforce replay protection with 5-minute limited-use App Check tokens. If you call a protected model without enabling limited-use tokens, the request fails with: ```text HTTP 403: "To access this model, you must enforce Firebase App Check" ``` To resolve this error on Web, initialize `getAI` with `useLimitedUseAppCheckTokens: true`: ```javascript const ai = getAI(app, { backend: new GoogleAIBackend(), useLimitedUseAppCheckTokens: true, }); ``` This instructs the SDK to fetch fresh, short-lived limited-use tokens (such as via reCAPTCHA Enterprise or the debug provider) for requests rather than reusing standard cached App Check tokens. ## Core Capabilities Text-Only Generation ```JavaScript async function generateText(prompt) { const result = await model.generateContent(prompt); const response = await result.response; return response.text(); } ``` ## Multimodal (Text + Images/Audio/Video/PDF input) Firebase AI Logic accepts Base64 encoded data or specific file references. ```JavaScript // Helper to convert file to base64 generic object async function fileToGenerativePart(file) { const base64EncodedDataPromise = new Promise((resolve) => { const reader = new FileReader(); reader.onloadend = () => resolve(reader.result.split(',')[1]); reader.readAsDataURL(file); }); return { inlineData: { data: await base64EncodedDataPromise, mimeType: file.type, }, }; } async function analyzeImage(prompt, imageFile) { const imagePart = await fileToGenerativePart(imageFile); const result = await model.generateContent([prompt, imagePart]); return result.response.text(); } ``` ## Chat Session (Multi-turn) Maintain history automatically using startChat. ```JavaScript const chat = model.startChat({ history: [ { role: "user", parts: [{ text: "Hello, I am a developer." }], }, { role: "model", parts: [{ text: "Great to meet you. How can I help with code?" }], }, ], }); async function sendMessage(msg) { const result = await chat.sendMessage(msg); return result.response.text(); } ``` ## Streaming Responses For real-time UI updates (like a typing effect). ```JavaScript async function streamResponse(prompt) { const result = await model.generateContentStream(prompt); for await (const chunk of result.stream) { const chunkText = chunk.text(); console.log("Stream chunk:", chunkText); // Update UI here } } ``` Generate Images with Nano Banana ```Javascript import { initializeApp } from "firebase/app"; import { getAI, getGenerativeModel, GoogleAIBackend, ResponseModality } from "firebase/ai"; // Initialize FirebaseApp const firebaseApp = initializeApp(firebaseConfig); // Initialize the Gemini Developer API backend service const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() }); // Create a `GenerativeModel` instance with a model that supports your use case const model = getGenerativeModel(ai, { model: "", // [AGENT] Replace with the latest image model from https://firebase.google.com/docs/ai-logic/models.md.txt // Configure the model to respond with text and images (required) generationConfig: { responseModalities: [ResponseModality.TEXT, ResponseModality.IMAGE], }, }); // Provide a text prompt instructing the model to generate an image const prompt = 'Generate an image of the Eiffel Tower with fireworks in the background.'; // To generate an image, call `generateContent` with the text input const result = await model.generateContent(prompt); // Handle the generated image try { const inlineDataParts = result.response.inlineDataParts(); if (inlineDataParts?.[0]) { const image = inlineDataParts[0].inlineData; console.log(image.mimeType, image.data); } } catch (err) { console.error('Prompt or candidate was blocked:', err); } ``` ## Advanced Features Structured Output (JSON) Enforce a specific JSON schema for the response. ```JavaScript import { getGenerativeModel, Schema } from "firebase/ai"; const jsonModel = getGenerativeModel(ai, { model: "", // [AGENT] Replace with the latest model from https://firebase.google.com/docs/ai-logic/models.md.txt generationConfig: { responseMimeType: "application/json", // Optional: Define a schema responseSchema: Schema.object({ ... }) } }); async function getJsonData(prompt) { const result = await jsonModel.generateContent(prompt); return JSON.parse(result.response.text()); } ``` On-Device AI (Hybrid) Automatically switch between local Gemini Nano and cloud models based on device capability. The Firebase JavaScript SDK checks for Gemini Nano's availability (after installation) and switches between on-device or cloud-hosted prompt execution. This requires specific steps to enable model usage in the Chrome browser, more info in the [hybrid inference documentation for Web](https://firebase.google.com/docs/ai-logic/hybrid/web/get-started.md.txt). ```JavaScript import {getGenerativeModel, InferenceMode } from "firebase/ai"; const hybridModel = getGenerativeModel(ai, { mode: InferenceMode.PREFER_ON_DEVICE }); ``` ## App Check See [App Check with reCAPTCHA Enterprise](https://firebase.google.com/docs/app-check/web/recaptcha-enterprise-provider.md.txt) for setup instructions. App Check debug tokens for local development and CI/CD: - **Local development**: Set `self.FIREBASE_APPCHECK_DEBUG_TOKEN = true;` before initializing App Check (generates a token in the browser console; do not hardcode secret strings in client code). - **CI/CD**: Pass the pre-provisioned token from the environment instead (e.g. `self.FIREBASE_APPCHECK_DEBUG_TOKEN = process.env.APP_CHECK_DEBUG_TOKEN`). ### Debug Token Persistence When testing AI Logic on Web with App Check, clearing site data, using incognito/private windows, or switching browsers generates a new debug token when `self.FIREBASE_APPCHECK_DEBUG_TOKEN = true` is used. To avoid this debug token churn without leaking secrets into client bundles, load a stable token from a gitignored local environment file: > [!WARNING] **CRITICAL: Never Hardcode or Commit Debug Tokens** Never hardcode > debug token strings in web source code. Always load them from a local, > gitignored environment file. ```javascript import { initializeAppCheck, ReCaptchaEnterpriseProvider } from "firebase/app-check"; if (typeof self !== "undefined") { if (typeof process !== "undefined" && process.env.NODE_ENV === "development") { // ✅ SAFE: Load dynamically from Next.js environment variable; fallback to true to auto-generate self.FIREBASE_APPCHECK_DEBUG_TOKEN = process.env.NEXT_PUBLIC_APP_CHECK_DEBUG_TOKEN || true; } else if (typeof import.meta !== "undefined" && import.meta.env?.DEV) { // ✅ SAFE: Load dynamically from Vite environment variable; fallback to true to auto-generate self.FIREBASE_APPCHECK_DEBUG_TOKEN = import.meta.env.VITE_APPCHECK_DEBUG_TOKEN || true; } } const appCheck = initializeAppCheck(app, { provider: new ReCaptchaEnterpriseProvider("/* reCAPTCHA site key */"), isTokenAutoRefreshEnabled: true, }); ```