> For the complete documentation index, see [llms.txt](https://developers-apps-in-toss.toss.im/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developers-apps-in-toss.toss.im/ai-vibe-coding/en/integration/connecting-firebase.md).

# Connecting Firebase

This guide explains how to integrate Firebase in the Apps in Toss (mini app) WebView environment. This document **Vite (React + TypeScript)** was written based on a project using that stack.

***

### Overview

Firebase is a service that provides various features such as authentication, databases, and file storage. It can also be used in the Apps in Toss WebView environment, but **Security settings and environment variable management**are important.

***

### 1. Getting Ready

* Firebase console account ([console.firebase.google.com](https://console.firebase.google.com))
* A project built with Vite (React + TypeScript)
* Node.js, npm (or yarn, pnpm)

### 2. Create a Firebase project

1. In the Firebase console **Create project**to create a new project.
2. Project settings → **Add app** → **Web (\</>)** select it.
3. Enter an app nickname and register it, and the configuration info (firebaseConfig) will appear as shown below.

```js
const firebaseConfig = {
  apiKey: '...',
  authDomain: '...',
  databaseURL: '...',
  projectId: '...',
  storageBucket: '...',
  messagingSenderId: '...',
  appId: '...',
  measurementId: '...'
}
```

### 3. Set environment variables

For security, it is recommended to manage Firebase configuration information as Vite environment variables.

At the project root, `.env` create a file and write it as shown below.

```bash
VITE_FIREBASE_API_KEY=your_api_key
VITE_FIREBASE_AUTH_DOMAIN=your-project.firebaseapp.com
VITE_FIREBASE_PROJECT_ID=your-project-id
VITE_FIREBASE_STORAGE_BUCKET=your-project.appspot.com
VITE_FIREBASE_MESSAGING_SENDER_ID=your_sender_id
VITE_FIREBASE_APP_ID=your_app_id
```

In code, `import.meta.env.VITE_FIREBASE_API_KEY`use it like this.

### 4. Install and initialize Firebase

Written based on the latest Firebase modular SDK (v12+).

```bash
npm install firebase
# or
yarn add firebase
```

`src/firebase/init.ts`

```ts
import { initializeApp, getApps } from 'firebase/app'
import { getAuth } from 'firebase/auth'
import { getFirestore } from 'firebase/firestore'
import { getStorage } from 'firebase/storage'

const firebaseConfig = {
  apiKey: import.meta.env.VITE_FIREBASE_API_KEY,
  authDomain: import.meta.env.VITE_FIREBASE_AUTH_DOMAIN,
  projectId: import.meta.env.VITE_FIREBASE_PROJECT_ID,
  storageBucket: import.meta.env.VITE_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: import.meta.env.VITE_FIREBASE_MESSAGING_SENDER_ID,
  appId: import.meta.env.VITE_FIREBASE_APP_ID,
}

const app = getApps().length ? getApps()[0] : initializeApp(firebaseConfig)

export const auth = getAuth(app)
export const db = getFirestore(app)
export const storage = getStorage(app)
```

> **Note:**
>
> * `databaseURL`is **Realtime Database**only needed when using it. If you're using Firestore, you can leave it out.
> * `measurementId`is needed when using **Firebase Analytics**(Google Analytics).

### 5. Firestore usage example

If you've initialized Firestore, you can read or write data inside a React component. Below is `App.tsx`the simplest example of reading and saving a single document.

```tsx
import { useState, useEffect } from 'react'
import { db } from './firebase/init'
import { doc, getDoc, setDoc } from 'firebase/firestore'

function App() {
  const [name, setName] = useState('')
  const [savedName, setSavedName] = useState('')

  // Read data from Firestore
  useEffect(() => {
    const fetchData = async () => {
      const ref = doc(db, 'users', 'exampleUser')
      const snap = await getDoc(ref)
      if (snap.exists()) {
        setSavedName(snap.data().name)
      }
    }
    fetchData()
  }, [])

  // Write data to Firestore
  const handleSave = async () => {
    const ref = doc(db, 'users', 'exampleUser')
    await setDoc(ref, { name })
    setSavedName(name)
    setName('')
  }

  return (
    <div style={{ padding: 24 }}>
      <h1>Simple Firestore Example</h1>
      <input
        value={name}
        onChange={(e) => setName(e.target.value)}
        placeholder="Enter name"
      />
      <button onClick={handleSave}>Save</button>
      <p>Saved name: {savedName || '(none)'}</p>

  )
}

export default App

```

#### How it works

* Reading data (`getDoc`)
  * Loads the Firestore users/exampleUser document once.
  * If the document exists, display the value of snap.data() on screen.
* Writing data (`setDoc`)
  * Overwrites and saves the entered name to Firestore.
  * If the document doesn't exist, a new one is created automatically.

<figure><img src="https://2128335993-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNbJTp2UkOUSb6YpQegOx%2Fuploads%2FCULa7xVM4LOfxoSSRKB5%2Fimage.png?alt=media&amp;token=c75221bb-940b-4e3a-b718-42d39cdc9a66" alt=""><figcaption></figcaption></figure>

> Firestore supports many features beyond single documents.
>
> * Real-time subscription: `onSnapshot(doc(...))`will automatically update the UI whenever the document changes.
> * Working with collections: `collection()`, `addDoc()`can be used to add and load multiple documents.
> * File storage: `getStorage()`to `Storage`connect and upload images or files.
> * Authentication integration: `getAuth()`can be used together with it to save user-specific data.

### 6. Security checklist

* Manage sensitive information with environment variables
  * Do not write the Firebase API key, service account key, etc. directly in code and `.env`manage them as environment variables.
* Don't upload environment files to Git, etc.
  * `.env` The file `.gitignore`must be added.
  * If a key is exposed, immediately reissue it in the Firebase console and review the relevant project permissions.
* Set Firebase security rules
  * Firestore / Storage are basically open to all users.
  * Before deployment, make sure to modify the rules so that only authenticated users can access them.
* Check origin restrictions
  * In the Firebase console's Authentication / Hosting / API Key settings, restrict the allowed domains.
  * If you allow only the mini app (WebView) domain, you can prevent unauthorized access.

{% hint style="info" %}
**Allowed domains**

```
https://<appName>.apps.tossmini.com : production environment
https://<appName>.private-apps.tossmini.com : console QR test environment
```

{% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://developers-apps-in-toss.toss.im/ai-vibe-coding/en/integration/connecting-firebase.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
