Setup Firestore for Nuxt.js

April 10, 2020

Install @nuxtjs/firebase

npm i nuxt
npm i firebase
npm i @nuxtjs/firebase

Edit nuxt.config.js

export default {
  modules: [
    '@nuxtjs/firebase',
  ],
  firebase: {
    config: {
      apiKey: '<apiKey>',
      authDomain: '<authDomain>',
      databaseURL: '<databaseURL>',
      projectId: '<projectId>',
      storageBucket: '<storageBucket>',
      messagingSenderId: '<messagingSenderId>',
      appId: '<appId>',
      measurementId: '<measurementId>'
    },
    services: {
      firestore: true
    }
  }
}

NOTE: To get config, goto Firebase Console -> Project -> Project settings (click Gear icon beside Project Overview), click Add app if you haven’t done so, else Your apps -> Firebase SDK snippet -> Config.

NOTE: You probably want to setup Firebase Authentication as well.

Query

Option 1: asyncData with spa mode

Make sure nuxt.config.js is spa mode (without SSR)

export default {
  // mode: 'universal',
  mode: 'spa',
}

Query

<script>
export default {
  async asyncData ({ app, params }) {
    const db = app.$fireStore
    const placeId = params.id

    const placeRef = db.collection('place')
    // const snapshot = await placeRef.doc(placeId).get()
    const snapshot = await placeRef.where('parent_ids', 'array-contains', placeId).get()
    const items = snapshot.docs.map(doc => {
      const item = doc.data()
      item.id = doc.id
      return item
    })
    return { items }
  }
}
</script>

Option 2: asyncData with universal mode

Firebase Authentication token is missing with universal mode (during server render), unless you enable Firebase admin authorization

NOTE: I didn’t test this

Option 3: query during mounted

<script>
export default {
  data() {
    return {
      placeId: this.$route.params.id,
      items: [],
    }
  },
  async mounted() {
    const db = this.$fireStore
    const placeRef = db.collection('place')
    const snapshot = await placeRef.where('parent_ids', 'array-contains', this.placeId).get()
    this.items = snapshot.docs.map(doc => {
      const item = doc.data()
      item.id = doc.id
      return item
    })
  },
}
</script>
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.