VueFire Documentation

website·Indexed 19 days ago

https://vuefire.vuejs.org/

Official documentation for VueFire, a library providing tools and composable functions to manage reactive Firebase data within Vue applications. It includes support for Firebase Authentication, Firestore, Realtime Database, and Storage, with a dedicated official module for Nuxt.js that handles SSR and environment variables.

Tokens
17.4K
Snippets
103
Records
149
Agent score
99%

What's inside VueFire

  1. Overview of VueFire for real-time Firebase bindings

    VueFire is a library designed to create real-time bindings between a Vue application and either a Firebase Realtime Database (RTDB) or Firebase Cloud Firestore. Its primary purpose is to keep local application data automatically in sync with remote database changes, removing the need to manually manage listeners, handle document changes (added, modified, removed), or manually manage Firestore references.
  2. Use VueFire auto-imports in Nuxt

    The nuxt-vuefire module automatically imports the most commonly used functions from vuefire, allowing you to use them in your components without explicit import statements.
  3. Use VueFire composables for declarative Firebase integration

    VueFire provides composables designed to align with Vue's declarative approach. It automatically handles complex Firebase patterns, including Nested Collections and Document References, reducing the amount of manual boilerplate code required to sync data.
  4. Use VueFire with Nuxt Server Side Rendering (SSR)

    Nuxt VueFire is compatible with both SSR-enabled and SSR-disabled configurations. No special configuration or manual setup is required to enable SSR support, as it is handled automatically by the library.
  5. Create reactive data source bindings

    To change the document or collection being observed dynamically (e.g., based on a URL parameter), pass a reactive source to the composable. The source can be a getter function, a computed() property, or a shallowRef(). If a null value is returned by the source, VueFire will treat it as having no data source and will not attempt to observe it.
    const route = useRoute()
    
    // Option 1: Using a getter (lightest option)
    useDocument(() => doc(collection(db, 'contacts'), route.params.id))
    
    // Option 2: Using computed
    const contactSource = computed(() => doc(collection(db, 'contacts'), route.params.id))
    const contact = useDocument(contactSource)
    
    // Option 3: Using shallowRef (better performance than ref())
    const asRef = shallowRef(doc(collection(db, 'contacts'), route.params.id))
    useDocument(asRef)
    
    // Conditional binding (returns null if user is not logged in)
    const user = useCurrentUser()
    const myContactList = useCollection(() =>
      user.value ? collection(db, 'users', user.value.id, 'contacts') : null
    )
    
  6. Create a Custom Nitro Preset for Firebase Functions

    To customize Firebase Functions configuration (such as setting the region), create a custom Nitro preset instead of using the default firebase preset. This involves creating a preset folder with an entry file and a configuration file, then pointing nitro.preset to that folder in nuxt.config.ts.
    // preset/entry.ts
    import '#internal/nitro/virtual/polyfill'
    import { onRequest } from 'firebase-functions/v2/https'
    
    const nitroApp = useNitroApp()
    const config = useRuntimeConfig()
    
    export const server = onRequest(
      {
        // Set region and other options here
      },
      toNodeListener(nitroApp.h3App)
    )
    // preset/nitro.config.ts
    import { fileURLToPath } from 'node:url'
    import type { NitroPreset } from 'nitropack'
    
    export default {
      extends: 'firebase',
      entry: fileURLToPath(new URL('./entry.ts', import.meta.url)),
    } satisfies NitroPreset
    // nuxt.config.ts
    export default defineNuxtConfig({
      nitro: {
        preset: './preset',
      },
    })
    
  7. Implement SSR state hydration with Vitesse

    When using VueFire with the Vitesse template, you must synchronize the server-side state with the client to avoid redundant data fetching. This is achieved using useSSRInitialState. On the server, it initializes the state object; on the client, it re-hydrates the application using that state.
    // src/modules/vuefire.ts
    import { initializeApp } from 'firebase/app'
    import { VueFire, useSSRInitialState } from 'vuefire'
    import type { UserModule } from '~/types'
    
    export const install: UserModule = ({ isClient, initialState, app }) => {
      const firebaseApp = initializeApp({
        // your config
      })
    
      app.use(VueFire, { firebaseApp })
    
      if (isClient) {
        // reuse the initial state on the client
        useSSRInitialState(initialState.vuefire, firebaseApp)
      } else {
        // on the server we ensure all the data is retrieved in this object
        initialState.vuefire = useSSRInitialState(
          undefined,
          firebaseApp,
        )
      }
    }
  8. Install VueFire in a Nuxt project

    To set up VueFire in Nuxt, install the Firebase JS SDK and add the nuxt-vuefire module using the Nuxt CLI. If Server-Side Rendering (SSR) is enabled, you must also install firebase-admin and its peer dependencies.
    # Basic installation
    npm install firebase
    npx nuxi@latest module add vuefire
    
    # Additional dependencies required for SSR
    npm install firebase-admin firebase-functions @firebase/app-types
  9. Wait for VueFire data when using composables outside components

    When using VueFire composables (like useDocument) inside a Pinia store or other non-component files, VueFire cannot automatically call onServerPrefetch(). You must manually wait for pending promises in the component that consumes the data using usePendingPromises().
    <script setup>
    import { useQuizStore } from '~/stores/quiz'
    import { usePendingPromises } from 'vuefire'
    
    const quizStore = useQuizStore()
    
    // Option 1: Using onServerPrefetch
    onServerPrefetch(() => usePendingPromises())
    
    // Option 2: Using <Suspense> with top-level await
    await usePendingPromises()
    </script>
  10. Configure Firebase services as Nuxt plugins

    In Nuxt, you can create a plugin in the plugins/ directory to initialize Firebase services. Use the .client suffix (e.g., analytics.client.ts) for services that only run on the client side, such as Firebase Analytics. Use provide to make the service available globally via the Nuxt context.
    // plugins/analytics.client.ts
    import {
      type Analytics,
      initializeAnalytics,
      isSupported,
    } from 'firebase/analytics'
    import { useFirebaseApp } from 'vuefire'
    
    export default defineNuxtPlugin(async () => {
      const firebaseApp = useFirebaseApp()
    
      let analytics: Analytics | null = null
      if (await isSupported()) {
        analytics = initializeAnalytics(firebaseApp)
      }
    
      return {
        provide: {
          analytics,
        },
      }
    })
    
  11. Install VueFireAuth module

    To enable Firebase Authentication in a Vue app, add the VueFireAuth module to the VueFire plugin configuration. This automatically initializes and injects the Firebase Auth module.
    import { VueFire, VueFireAuth } from 'vuefire'
    app.use(VueFire, {
      firebaseApp: createFirebaseApp(),
      modules: [
        // ... other modules
        VueFireAuth(),
      ],
    })
  12. Install VueFire and Firebase SDK

    To use VueFire, you must install both the vuefire package and the firebase JS SDK. VueFire requires Firebase JS SDK version 9 or higher and is compatible with both Vue 2 and Vue 3.
    # Using npm
    npm i vuefire firebase
    
    # Using yarn
    yarn add vuefire firebase
    
    # Using pnpm
    pnpm i vuefire firebase