> 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/integrating-firebase.md).

# Integrating Firebase

This guide explains how to integrate Firebase in the Appintoss (mini app) WebView environment. This document **Vite (React + TypeScript)** is written based on a project built with.

***

### Overview

Firebase is a service that provides various features such as authentication, databases, and file storage. It can be used the same way in the Appintoss WebView environment as well, but **security settings and environment variable management**are important.

***

### 1. Getting Started

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

### 2. Create a Firebase project

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

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

### 3. Set environment variables

For security, we recommend managing Firebase configuration info as Vite environment variables.

In the project root, `.env` create a file and write it like 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 **only needed when using**Realtime Database. If you use Firestore, you can omit it.
> * `measurementId`is **needed when using**Firebase Analytics (Google Analytics).

### 5. Firestore usage example

If Firestore is initialized, you can read and 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 only once.
  * If the document exists, the value from snap.data() is displayed on the screen.
* Writing data (`setDoc`)
  * overwrites and saves the entered name to Firestore.
  * If the document does not exist, a new one is created automatically.

<figure><img src="/files/39fbea7e9f72d3c33345312f0a4420a495e9afce" alt=""><figcaption></figcaption></figure>

> Firestore supports many features in addition to single documents.
>
> * Real-time subscription: `onSnapshot(doc(...))`updates the UI automatically whenever the document changes.
> * Working with collections: `collection()`, `addDoc()`let you add and load multiple documents.
> * File storage: `getStorage()`to `Storage`connect and upload images or files.
> * Authentication integration: `Using it with getAuth()`makes it possible to save data per user.

### 6. Security checklist

* Manage sensitive information with environment variables
  * Firebase API keys, service account keys, etc. should not be written directly in code, `.env`manage them with
* Do not upload environment files to Git, etc.
  * `.env` The file `.gitignore`must be added to.
  * If a key is exposed, immediately reissue it in the Firebase console and review the permissions of related projects.
* Set up Firebase security rules
  * Firestore / Storage are publicly accessible to all users by default.
  * Before deployment, be sure to modify the rules so that only authenticated users can access them.
* Check origin restrictions
  * In Firebase console 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/integrating-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.
