Vue 2+ Firebase Tutorial – Integrate Cloud Firestore with VueFire

Last updated on by Digamber
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 realtime across all connected devices. We will use the VueFire package to take advantage of Firebase. It makes our development work, even simpler by providing direct access to Firebase objects.

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.

We all know Firebase is a widely used database cloud infrastructure for client-side apps. Firebase is BaaS (Backend-as-a-Service) based product that allows web developers to build web or mobile applications without going through the complication of backend.

It offers powerful features to manage the backend. You can easily create APIs and manage data on the cloud database. It can be used with other frameworks and platforms such as Angular, React, Android, or iOS.

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

To install the Vue project, first, we need to 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 4.3.0.

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.

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

VueFire makes it super easy to bind firestore collections and documents and keep your local data always up to date with their remote versions.

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

# NPM
$ npm i firebase vuefire --save


# Yarn
$ yarn add firebase 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>

As se know 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.