Firebase

Google Firebase (docs here) can provide a variety of serverless features for your site (authentication, database and file storage, cloud functions, and more). With a few steps, you can get rolling using Firebase in your Vue applications.

1) Install the Firebase package with npm

Execute this command in the root directory of your project to install the package.

npm install --save firebase

2) Create a config file with your developer credentials

Create a config file with your Firebase developer credentials (in this example, we are using the file name "firebaseConfig" and placing it in the components directory). You should be able to find your credentials after creating an account and logging in with Firebase- you'll need to fill in the fields below with the specific values for your app. To make it easier to manage, this file is created separately and imported when initializing your app.

export default {
  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",
};

3) Create an init file with each of the features you want to use

Now you can create another file for initializing each of the features you need (here name firebaseInit in the components directory). Notice how the firebaseConfig is imported from the file you just created in the previous step. The command firebase.initializeApp() initializes Firebase in your project with your credentials and should only be called once. Then you can create const variables for each of the features (realtime database, firestore database, bulk storage, etc). Finally, export those variables to make them available to the components in your application where you want to use them.

import firebase from 'firebase'
import firebaseConfig from './firebaseConfig'
const firebaseApp = firebase.initializeApp(firebaseConfig);
const rtdb = firebaseApp.database();
const db = firebaseApp.firestore();
const storage = firebaseApp.storage();
export {rtdb as rtdb, db as db, storage as storage, firebase as firebase};

4) Use the features in your individual components or in your Vuex store

Below is an example of using firebase to log a user in to their account (perhaps on a Sign In page). Notice how firebase is imported from the firebaseInit file where it was initialized. The same can be done for the rtdb, db, and storage variables you created your init file.

import {firebase} from '@/components/firebaseInit'

export default {
  name: 'Signin',
  data() {
    return {
      email: '',
      password: ''
    }
  },
  methods: {
    login: function() {
      firebase.auth().signInWithEmailAndPassword(this.email, this.password).then(
        (user) => {
          console.log(user);
          this.$router.replace('home')
        },
        (err) => {
          alert('Oops. ' + err.message)
        }
      );
    },
  }
}