firebasenuxt.js

Place to initialize Firebase in Nuxt.js app


I'm writing a web app with Nuxt.js and Firebase. In which file do I need to initialize the Firebase? In other words, where to put this code snippet?

var config = {
    apiKey: "xxxxxxxxxx",
    authDomain: "xxxxxxxxx.firebaseapp.com",
    databaseURL: "https://xxxxxxxx.firebaseio.com",
    projectId: "xxxxxxxxx",
    storageBucket: "xxxxxxxxxxx.appspot.com",
    messagingSenderId: "xxxxxxxxxx"
};
firebase.initializeApp(config);

Solution

  • Create file firebase.js in folder plugins.

    import firebase from 'firebase'
    import 'firebase/firestore' //if use firestore
    
    if (!firebase.apps.length) {
      firebase.initializeApp({
        apiKey: "xxx",
        authDomain: "xxx",
        databaseURL: "xxx",
        projectId: "xxx",
        storageBucket: "xxx",
        messagingSenderId: "xxx"
      })
    }
    
    firebase.firestore().settings({ timestampsInSnapshots: true })
    
    const db = firebase.firestore()
    const storage = firebase.storage() //if use storage
    
    export { storage, db }
    

    In component:

    import { db } from '~/plugins/firebase.js'
    
    data() {
      return {
        users: []
      }
    },
    mounted() {
      db.collection("users").get().then((querySnapshot) => {
        this.users = querySnapshot.docs.map(doc =>
          Object.assign({ id: doc.id }, doc.data())
        )
      })
    }