Setup Firestore for Nuxt.js

Apr 10, 2020

Install @nuxtjs/firebase

npm i nuxtnpm i firebasenpm 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>

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.