> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/genkit-ai/genkit/llms.txt
> Use this file to discover all available pages before exploring further.

# Firebase plugin

> Use Firestore as a vector store for RAG, enable Firebase Genkit Monitoring, and integrate Firebase Auth with Genkit flows.

The Firebase plugin extends Genkit with three capabilities:

1. **Firestore vector search** — use Cloud Firestore's native vector similarity search as a retriever for RAG pipelines.
2. **Firebase Genkit Monitoring** — export traces, metrics, and logs to the Google Cloud Observability suite through a single call.
3. **Firebase Auth integration** — verify Firebase ID tokens to protect HTTP-triggered flows (Go only, see `auth.go`).

## Installation

<Tabs>
  <Tab title="TypeScript">
    <CodeGroup>
      ```bash npm theme={null}
      npm install @genkit-ai/firebase
      ```

      ```bash pnpm theme={null}
      pnpm add @genkit-ai/firebase
      ```
    </CodeGroup>
  </Tab>

  <Tab title="Go">
    ```bash theme={null}
    go get github.com/firebase/genkit/go/plugins/firebase
    ```
  </Tab>
</Tabs>

## Configuration

<Tabs>
  <Tab title="TypeScript">
    The TypeScript Firebase plugin does not use a plugin initializer — it exports standalone functions (`defineFirestoreRetriever`, `enableFirebaseTelemetry`) that you call directly.

    Make sure the Firebase Admin SDK is initialised before using these functions:

    ```ts theme={null}
    import * as admin from 'firebase-admin';

    admin.initializeApp();
    ```
  </Tab>

  <Tab title="Go">
    ```go theme={null}
    import (
      "github.com/firebase/genkit/go/genkit"
      "github.com/firebase/genkit/go/plugins/firebase"
    )

    g := genkit.Init(ctx,
      genkit.WithPlugins(&firebase.Firebase{
        ProjectId: "my-firebase-project",
        // Or: App: existingFirebaseApp,
      }),
    )
    ```

    Set `FIREBASE_PROJECT_ID` in the environment as an alternative to the inline `ProjectId` field. Provide either `ProjectId` or `App`, not both.
  </Tab>
</Tabs>

## Firestore as a vector store

Firestore's [vector search](https://firebase.google.com/docs/firestore/vector-search) lets you find documents whose embedding vectors are nearest to a query embedding. Genkit wraps this with a retriever so your flows can use it for RAG.

### Prerequisites

Before querying, create a vector index on the Firestore collection:

```bash theme={null}
gcloud firestore indexes composite create \
  --project=my-project \
  --collection-group=documents \
  --query-scope=COLLECTION \
  --field-config field-path=embedding,vector-config='{"dimension":"768","flat":"{}"}'
```

### Defining a retriever

<Tabs>
  <Tab title="TypeScript">
    ```ts theme={null}
    import { genkit } from 'genkit';
    import { googleAI } from '@genkit-ai/google-genai';
    import { defineFirestoreRetriever } from '@genkit-ai/firebase';
    import { initializeApp } from 'firebase-admin/app';
    import { getFirestore } from 'firebase-admin/firestore';

    initializeApp();
    const db = getFirestore();

    const ai = genkit({ plugins: [googleAI()] });

    const docsRetriever = defineFirestoreRetriever(ai, {
      name: 'documents',
      firestore: db,
      collection: 'documents',
      embedder: googleAI.embedder('gemini-embedding-001'),
      vectorField: 'embedding',
      contentField: 'text',
      // Optional: include metadata fields in results
      metadataFields: ['title', 'source', 'createdAt'],
      // Distance measure: 'COSINE' (default), 'EUCLIDEAN', or 'DOT_PRODUCT'
      distanceMeasure: 'COSINE',
      // Only return documents within this distance
      distanceThreshold: 0.7,
    });
    ```
  </Tab>

  <Tab title="Go">
    ```go theme={null}
    import (
      "github.com/firebase/genkit/go/plugins/firebase"
      "cloud.google.com/go/firestore"
    )

    retriever, err := firebase.DefineRetriever(ctx, g, firebase.RetrieverOptions{
      Name:            "documents",
      Collection:      "documents",
      Embedder:        genkit.LookupEmbedder(g, "googleai/gemini-embedding-001"),
      VectorField:     "embedding",
      ContentField:    "text",
      Limit:           10,
      DistanceMeasure: firestore.DistanceMeasureCosine,
      MetadataFields:  []string{"title", "source"},
    })
    ```
  </Tab>
</Tabs>

### Querying the retriever

<Tabs>
  <Tab title="TypeScript">
    ```ts theme={null}
    const docs = await ai.retrieve({
      retriever: docsRetriever,
      query: 'How does RAG work?',
      options: {
        limit: 5,
        // Optional: filter by metadata field
        where: { source: 'official-docs' },
      },
    });

    // docs is Document[] — use it to build the prompt
    const context = docs.map(d => d.text()).join('\n\n');
    ```
  </Tab>

  <Tab title="Go">
    ```go theme={null}
    docs, err := genkit.Retrieve(ctx, g, retriever,
      ai.WithQuery(ai.DocumentFromText("How does RAG work?", nil)),
    )
    ```
  </Tab>
</Tabs>

### Indexing documents

Indexing (writing embeddings to Firestore) is handled outside the plugin — you embed each document and write it to the collection using the Firebase Admin SDK:

```ts theme={null}
async function indexDocument(text: string, title: string) {
  const [embedding] = await ai.embed({
    embedder: googleAI.embedder('gemini-embedding-001'),
    content: text,
  });

  await db.collection('documents').add({
    text,
    title,
    embedding: FieldValue.vector(embedding.embedding),
    createdAt: FieldValue.serverTimestamp(),
  });
}
```

## Firebase Genkit Monitoring

Enable telemetry export to Google Cloud Trace, Logging, and Monitoring:

<Tabs>
  <Tab title="TypeScript">
    ```ts theme={null}
    import { enableFirebaseTelemetry } from '@genkit-ai/firebase';

    // Call once at app startup, before any flows run
    await enableFirebaseTelemetry({
      // Optional: override auto-detected project ID
      // projectId: 'my-project',
    });
    ```

    `enableFirebaseTelemetry` delegates to the `@genkit-ai/google-cloud` plugin internally, so all Google Cloud Observability features are available.
  </Tab>

  <Tab title="Go">
    ```go theme={null}
    import (
      "github.com/firebase/genkit/go/plugins/firebase"
    )

    // Enable telemetry export for a Firebase project
    if err := firebase.EnableTelemetry(ctx, &firebase.FirebaseTelemetryOptions{
      ProjectID: "my-firebase-project",
      // Credentials: googleCredentials, // optional
    }); err != nil {
      log.Fatal(err)
    }
    ```

    The Go plugin auto-detects the project ID from `FIREBASE_PROJECT_ID`, `GOOGLE_CLOUD_PROJECT`, or `GCLOUD_PROJECT` environment variables.
  </Tab>
</Tabs>

<Note>
  When deploying to Firebase App Hosting or Cloud Run, the project ID and credentials are automatically inferred from the runtime environment. No additional configuration is needed.
</Note>

## Firebase Auth for flow security

In Go, the Firebase plugin provides an `Auth` client you can use to verify Firebase ID tokens in HTTP middleware:

```go theme={null}
// Retrieve the Auth client from the plugin
firebasePlugin, _ := genkit.LookupPlugin(g, "firebase").(*firebase.Firebase)
authClient, _ := firebasePlugin.Auth(ctx)

// In your HTTP handler:
token, err := authClient.VerifyIDToken(ctx, idTokenFromRequest)
if err != nil {
  http.Error(w, "Unauthorized", http.StatusUnauthorized)
  return
}
// token.UID is the authenticated user
```

## Deploying to Firebase App Hosting

Firebase App Hosting has native support for Genkit. Set up Firebase and deploy:

```bash theme={null}
firebase init apphosting
firebase deploy
```

See the [Firebase deployment guide](/deployment/firebase) for a complete walkthrough including environment variable configuration and telemetry setup.

## Related pages

<CardGroup cols={2}>
  <Card title="RAG guide" href="/concepts/rag">
    Build retrieval-augmented generation pipelines end-to-end.
  </Card>

  <Card title="Firebase deployment" href="/deployment/firebase">
    Deploy Genkit flows to Firebase App Hosting.
  </Card>

  <Card title="Vertex AI plugin" href="/plugins/vertex-ai">
    Vertex AI Vector Search for larger-scale retrieval.
  </Card>

  <Card title="Observability" href="/deployment/observability">
    Traces, metrics, and logging in production.
  </Card>
</CardGroup>
