How to Integrate Firebase Authentication in Vue Js

Vue Firebase authentication tutorial; In our previous tutorial, we harnessed the true power of Firebase and comprehended how to create a basic CRUD app using Cloud Firestore. So, we are now a bit acquainted with the Firebase.

Similarly, in this Vue Firebase auth example, we will teach you how to add authentication in the Vue Js app using Firebase auth provider.

You will create a basic vue auth app, learn to add Firebase in vue, use firebase authentication services for user registration, user sign-in and allow the logged-in users to access the dashboard page.

When you complete this tutorial, you will understand how firebase authentication works in the vue ecosystem. We will demystify some common concepts eloquently, like vue firebase signup with email and password and vue firebase login with email and password.

Let us understand how to add authentication in Vue Js app using Firebase auth providers.

Vue Js Firebase Authentication Example

  • Step 1: Create New Vue App
  • Step 2: Obtain Firebase SDK
  • Step 3: Set Up Firebase in Vue
  • Step 4: Create Vue Auth Components
  • Step 5: Configure Routes and Navigation
  • Step 6: Register New User with Email/Password
  • Step 7: Signin with Email/Password
  • Step 8: User Logout in Vue Firebase
  • Step 9: Start App in Browser

Create New Vue App

We will use the Vue CLI for Vue auth development; on the command prompt, type the suggested command and install the tool globally.

Similarly, at the same time we can create a vue app and get inside the project root.

npm install -g @vue/cli

vue create vue-galactic-auth

cd vue-galactic-auth

Designing authentication pages is a time taking process. To reduce the time of HTML and CSS coding, we will install and use Bootstrap.

npm i bootstrap

Next, open the src/main.js and import the bootstrap CSS path.

import 'bootstrap/dist/css/bootstrap.min.css'

Obtain Firebase SDK

Firebase is easy to add in your project with its simple SDK, to get the credentials visit firebase.google.com.

Next, let’s create a new firebase project.

Firebase Create Account

Next, do provide the project name.

Create a project

Next, add Firebase to your application.

add Firebase to app

Next, give name to your project.

add firebase

Now, you need to copy Firebase SDK, and we will late register it into the Vue app.

Firebase configuration keys

Eventually, click on Authentication; after that, click on to sign-in method and enable the Email/Password auth provider.

Firebase Authentication

Set Up Firebase in Vue

Next, execute the provided command to install the firebase package in vue.

npm install firebase

Make the connection between Firebase and Vue, add the provided code in src/main.js, import firebase services and tie with the Firebase SDK and call the initializeApp() method.

import Vue from 'vue';
import App from './App.vue';
import 'bootstrap/dist/css/bootstrap.min.css';
import VueRouter from 'vue-router'
Vue.use(VueRouter)


// Database connection
import firebase from 'firebase/app';

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"
}
firebase.initializeApp(firebaseConfig);



new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

Create Vue Auth Components

Now, create following components to implement firebase auth in vue application:

=> components/LoginComponent.vue

=> components/RegisterComponent.vue

=> components/DashboardComponent.vue

Configure Routes and Navigation

Vue Router is the standard router library for Vue. It helps you add routes and evoke navigation in Vue js Single Page Applications; it offers the following features:

  • Nested route/view mapping
  • Customizable Scroll Behavior
  • Route params, query, wildcards
  • Fine-grained navigation control
  • Links with automatic active CSS classes
  • Modular, component-based router configuration
  • View transition effects powered by Vue.js’ transition system
  • HTML5 history mode or hash mode, with auto-fallback in IE9

So, go ahead, execute the below command and start adding the vue router package in vue.

npm install vue-router

Define the url within the routes array to display auth pages, create signin, user-register and dashboard routes, update code in the src/main.js file.

import Vue from 'vue';
import App from './App.vue';
import 'bootstrap/dist/css/bootstrap.min.css';
import VueRouter from 'vue-router'
Vue.use(VueRouter)


// Routers
const router = new VueRouter({
  mode: 'history',
  base: __dirname,
  routes: [
    { 
      path: '/register-user',
      name: 'register-user',
      component: () => import('./components/RegisterComponent.vue')
    },    
    { 
      path: '/signin',
      name: 'signin',
      component: () => import('./components/LoginComponent.vue')
    },
    { 
      path: '/dashboard',
      name: 'dashboard',
      component: () => import('./components/DashboardComponent.vue')
    }
  ]
});


// Database connection
import firebase from 'firebase/app';
const firebaseConfig = {
    apiKey: "AIzaSyCTzFxijZnHEp6olH4XojCd4H-Mqac-3Q8",
    authDomain: "fir-2731a.firebaseapp.com",
    projectId: "fir-2731a",
    storageBucket: "fir-2731a.appspot.com",
    messagingSenderId: "410469965499",
    appId: "1:410469965499:web:61eaf526ae6afe79a2139e"
}

firebase.initializeApp(firebaseConfig);

Vue.config.productionTip = false

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

The router-view brings the particular component in the view with the matched url, whereas the router link enables the navigation within the vue app, update code in src/App.vue file.

<template>
  <div>
    <div class="d-flex justify-content-center p-4 mb-3 bg-dark">
      <div>
          <router-link class="nav-link link-light" to="/signin">
             Login
          </router-link>
      </div>
      <div>
          <router-link class="nav-link link-light" to="/register-user">
             Register
          </router-link>
      </div>
    </div>

    <div class="container">
      <router-view></router-view>
    </div>
  </div>
</template>

Register New User with Email/Password in Vue

Get into the components/RegisterComponent.vue file, copy the entire below code snippet and paste. Create a simple form using Bootstrap elements, add a name, email and password input fields, import firebase, set a user object, access the createUserWithEmailAndPassword() method via auth() function.

<template>
    <div class="row d-flex justify-content-center">
        <div class="col-md-8 mt-5">
            <form @submit.prevent="onSubmit">
                <div class="form-group mb-3">
                    <label><strong>Name</strong></label>
                    <input type="text" class="form-control form-control-lg" v-model="user.name" />
                </div>

                <div class="form-group mb-3">
                    <label><strong>Email</strong></label>
                    <input type="email" class="form-control form-control-lg" v-model="user.email" />
                </div>

                <div class="form-group mb-3">
                    <label><strong>Password</strong></label>
                    <input type="password" class="form-control form-control-lg" v-model="user.password" />
                </div>

                <div class="d-grid">
                    <input type="submit" class="btn btn-primary btn-lg btn-block" value="Register User"/>
                </div>
            </form>
        </div>
    </div>
</template>


<script>
import firebase from "firebase";

export default {
  data() {
    return {
      user: {
        name: '',
        email: '',
        password: ''
      }
    };
  },
  methods: {
    onSubmit() {
      firebase.auth()
      .createUserWithEmailAndPassword(this.user.email, this.user.password)
      .then((response) => {
          response.user.updateProfile({
            displayName: this.user.name
          })
          .then(() => {
                alert('User successfully registered!')
                this.user = {
                    name: '',
                    email: '',
                    password: ''
                }
          });
      })
      .catch((err) => {
         console.log(err);
      });
    }
  }
};
</script>

Signin with Email/Password in Vue

Building login with email and password in vue with firebase is also facile; head over to components/LoginComponent.vue file, and update the file with the provided code.

<template>
    <div class="row d-flex justify-content-center">
        <div class="col-md-8 mt-5">
            <form @submit.prevent="onSubmit">
                <div class="form-group mb-3">
                    <label><strong>Email</strong></label>
                    <input type="email" class="form-control form-control-lg" v-model="user.email" />
                </div>

                <div class="form-group mb-3">
                    <label><strong>Password</strong></label>
                    <input type="password" class="form-control form-control-lg" v-model="user.password" />
                </div>

                <div class="d-grid">
                    <input type="submit" class="btn btn-primary btn-lg btn-block" value="Login"/>
                </div>
            </form>
        </div>
    </div>
</template>

<script>
import firebase from "firebase";
export default {
  data() {
    return {
      user: {
        email: '',
        password: ''
      }
    };
  },
  methods: {
    onSubmit() {
      firebase.auth()
      .signInWithEmailAndPassword(this.user.email, this.user.password).then(() => {
        this.$router.push('/dashboard')
       })
      .catch((err) => {
         console.log(err);
      });
    }
  }
};
</script>

User Logout in Vue Firebase

On successful login in our vue app, we will take you to the dashboard page; on the dashboard page, you can see the logged-in user’s information that we access using the user object.

However, it is just a simple login system; you can add numerous features to it, like add route-guard in vue to prevent unauthenticated users’ access so on and so forth.

Open components/DashboardComponent.vue file similarly update the suggested code.

<template>
    <div class="card">
        <h5 class="card-header">Dashboard</h5>
        <div class="card-body">
            <h5 class="card-title">{{user.displayName}}</h5>
            <p class="card-text">{{user.email}}</p>
            <a href="#" class="btn btn-primary" @click="signOut()">Signout</a>
        </div>
    </div>
</template>

<script>
import firebase from "firebase";

export default {
  data() {
    return {
      user: ''
    };
  },
  created() {
    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        this.user = user;
      } else {
        this.user = '';
      }
    });
  },
  methods: {
    signOut() {
      firebase.auth().signOut().then(() => {
        firebase.auth().onAuthStateChanged(() => {
          this.$router.push('/signin')
        })
      })
    }
  }
};
</script>

Start App in Browser

We have almost done everything, now start the app using the below command and use the given url to view the app.

npm run serve
http://localhost:8080

Add Firebase Authentication in Vue Js

Conclusion

So far, you have seen how Firebase makes our life easy through its auth provider service. It consists of tons of auth providers, which helps integrate basic authentication in Vue or any other front-end framework; thus, this Vue Firebase auth example is over.