How to Integrate Cloud Firestore with VueFire in Vue 2

Last Updated on by in Vue JS
This is a step by step Vue.JS and Firebase tutorial, In this tutorial we are going to explain how to integrate Cloud Firestore database in Vue application using the VueFire package.The Cloud Firestore helps storing and syncing data in real-time across all connected devices. We will use the VueFire package to implement Firebase in Vue Js 2 app. It makes our development work, simpler and at the same time facile.

The Vuefire offers logical solutions to create real-time bindings between a Firebase RTDB or a Firebase Cloud Firestore and your Vue application. It always keeps your local data in sync with remotes databases.

Firebase is a widely used database cloud infrastructure for client-side apps. It is a BaaS (Backend-as-a-Service) based product that helps web developers to create web applications without going through the complication of backend.

Here are some core server-side features that you can easily get with Firebase.

  • Cloud storage
  • Realtime update
  • Easy A/B Testing
  • Analytics Monitoring
  • Authentication support
  • Easy Server management
  • Real-time communication
  • Offline access to WEB SDK
  • Hosting and cloud storage
  • Push notifications support
  • Straightforward app hosting
  • Google Cloud IoT tools Integration support

Set Up Vue Project with Vue CLI

Install the latest Vue CLI 4 on our local development system.

npm install -g @vue/cli

Install the Vue project using the following command with Vue CLI.

vue create vue-firebase-setup

Vue CLI will ask your preferences, you may go with the following configurations:

Select “Manually select features”

Then choose “Router” “Vuex” and “CSS Pre-processors”

You can select your preferred CSS preprocessor from the given options. If you already have a configured Vue project, then you can then skip this step otherwise.

Node.js Gatsby error – “digital envelope routines::unsupported …”

Error: digital envelope routines::unsupported

opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
library: 'digital envelope routines',
reason: 'unsupported',
code: 'ERR_OSSL_EVP_UNSUPPORTED'

To remove above error for invoking the app, make sure to update the "scripts": [] array in package.json file.

"scripts": {
    "serve": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service serve",
    "build": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service build",
    "lint": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service lint"
},

Vue multi word error

To remove multi-word error warning, add the following code in vue.config.js file.

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false,
})

We are all set and ready to start the app on localhost server. Get inside the project folder and run the following command.

npm run serve

Install & Configure VueFire Package in Vue

Install firebase and vuefire modules in Vue app using either NPM or Yarn.

npm i firebase@^8.10.0 vuefire

We need to configure Firebase in the Vue app, so go to the main.js file to facilitate the VueFire plugin.

// src/main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

import { firestorePlugin } from 'vuefire'

Vue.use(firestorePlugin);
Vue.config.productionTip = false;

new Vue({
  router,
  store,
  render: function (h) { return h(App) }
}).$mount('#app')

Setting up a Firebase Project

We are going to create a Firebase project, follow the given below steps.

Open the Firebase console.

Click “CREATE NEW PROJECT”.

Creating Firebase Project

Next, click on “Add project” button and then enter your project name.

enter your project name

Here, you have to add Firebase to Vue app. It offers iOS, Android, and Web options to get started with; however, we will use web option.

add Firebase to Vue app

Provide an app name in order to register your Firebase app.

register your Firebase app

You will get the Firebase Configuration that you will need in a bit to make the connection between Vue and Firebase.

Firebase Config Keys

Next, click on Database > Cloud Firestore and then click on the “create database”.

Configure secure rules for Cloud Firestore. We are using Start in test mode for the demo purpose.

secure rules for Cloud Firestore

Make Firebase and Vue.js Connection

To make the connection between Firebase and Vue.js. We need to create a new file in the vue project, name it firebaseDatabase.js.

import * as firebase from 'firebase';

const firebaseConfig = {
    apiKey: "api-key",
    authDomain: "project-id.firebaseapp.com",
    databaseURL: "https://project-id.firebaseio.com",
    projectId: "project-id",
    storageBucket: "project-id.appspot.com",
    messagingSenderId: "sender-id",
    appId: "app-id",
    measurementId: "G-measurement-id"
}

const firebaseApp = firebase.initializeApp(firebaseConfig);

export const db = firebaseApp.firestore();

First, we took the Firebase configuration and defined the object for it.

Then, set the firebase configuration details as an argument in the Firebase.initializeApp(firebaseConfig) method.

Finally, exported the firebase database for all the Vue components.

Access Cloud Firestore via Vue.js to Display Data

We are all set to retrieve data from the Firebase database and display it to the web browser via the Vue component.

// views/Home.vue

<template>
  <ul>
    <li  v-for="student of students" :key="student['.key']">
      {{student.id}} <br>
      {{student.name}} <br>
      {{student.email}}
    </li>
  </ul>
</template>

<script>
import { db } from '../firebaseDatabase';

export default {
  components: {
      name: 'Home'
  },
  data() {
    return {
      students: []
    }
  },
  created: function() {
      db.collection('students').get()
      .then(snapshot => {
        snapshot.forEach(doc => {
          let item = doc.data()
          item.id = doc.id
          this.students.push(item)
        })
      })
  }  
}
</script>

Components are reusable instance, Vue components are sturdy instances. They accept data, computed, watch, methods, and lifecycle hooks.

By using the lifecycle hook, we get the data from firebase collection and inserted in the students array.

To verify the Firebase implementation in Vue App, Start the app using below command.

npm run serve

To get the complete code of this tutorial you can visit the this GitHub repo.