Vue 2 Tutorial- Firebase Authentication Example in Vue Js app

Vue 2 Firebase Authentication Tutorial Example

In this Vue.js 2 tutorial, we will learn how to integrate Firebase Authentication in a Vue app. We all also see how to register a user, log in, send password reset mail, and log out from the firebase app using the Vue.js application.

 

We will be using the Firebase database to add authentication to the Vue project from scratch. Firebase is a real-time database that offers Back-end-as-a-service.

Firebase offers tons of user authentication features such as Sign in/Signup with Email and Password, Facebook, Google, Twitter, GitHub, Phone Number, etc.

 

let’s see now which step s we have to follow to integrate the Firebase Authentication:

Step 1- Install and Setup Vue Project

Step 2- Add Bootstrap & Global CSS In Vue

Step 3- Create Components For Firebase Authentication

Step 4- Create Routers And Enable Navigation

Step 5- Set Up Firebase Project

Step 6- Add Firebase In Vue

Step 7- User registration with Email/Password

Step 8- Vue Firebase Login Example

Step 9- User Logout And Display Logged In User Data

Step 10- Conclusion

 

Step 1- Install And Setup Vue Project

The very basic step for starting is to install the latest version of Vue CLI:

npm install -g @vue/cli

 

Further, we create a new  Vue project and get inside the project folder using the below command::

vue create vue-firebase-auth && cd vue-firebase-auth

 

 

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 the above error for invoking the app, do remember to update the “scripts”: [] array in the 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"
},

 

Step 2- Add Bootstrap & Global CSS In Vue

Here, we will install the Bootstrap 5 module in the Vue project:

npm install bootstrap

 

Then, we will open the main.js file and import the Bootstrap path inside of it:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import 'bootstrap/dist/css/bootstrap.min.css'
Vue.config.productionTip = false
new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

 

Afterward, we have to include global styling in a Vue app.

Then, we need to create the src/assets/css folder after which we create the main.css file.

We will, now, add the global CSS path inside the main.js file right after the Bootstrap path:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import 'bootstrap/dist/css/bootstrap.min.css'
import '@/assets/css/main.css'
Vue.config.productionTip = false
new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

 

Then, we will add the below styling code in the assets/css/main.css file:

* {
  box-sizing: border-box;
}
body {
  background: #2554FF !important;
  min-height: 100vh;
  display: flex;
  font-weight: 400;
}
body,
html,
.App,
.vue-tempalte,
.vertical-center {
  width: 100%;
  height: 100%;
}
.navbar-light {
  background-color: #ffffff;
  box-shadow: 0px 14px 80px rgba(34, 35, 58, 0.2);
}
.vertical-center {
  display: flex;
  text-align: left;
  justify-content: center;
  flex-direction: column;    
}
.inner-block {
  width: 450px;
  margin: auto;
  background: #ffffff;
  box-shadow: 0px 14px 80px rgba(34, 35, 58, 0.2);
  padding: 40px 55px 45px 55px;
  border-radius: 15px;
  transition: all .3s;
}
.vertical-center .form-control:focus {
  border-color: #2554FF;
  box-shadow: none;
}
.vertical-center h3 {
  text-align: center;
  margin: 0;
  line-height: 1;
  padding-bottom: 20px;
}
label {
  font-weight: 500;
}
.forgot-password,
.forgot-password a {
  text-align: right;
  font-size: 13px;
  padding-top: 10px;
  color: #7a7a7a;
  margin: 0;
}
.forgot-password a {
  color: #2554FF;
}
.social-icons {
  text-align: center;
  font-family: "Open Sans";
  font-weight: 300;
  font-size: 1.5em;
  color: #222222;
}
.social-icons ul {
  list-style: none;
  margin: 0;
  padding: 0;
}
.social-icons ul li {
  display: inline-block;
  zoom: 1;
  width: 65px;
  vertical-align: middle;
  border: 1px solid #e3e8f9;
  font-size: 15px;
  height: 40px;
  line-height: 40px;
  margin-right: 5px;
  background: #f4f6ff;
}
.social-icons ul li a {
  display: block;
  font-size: 1.4em;
  margin: 0 5px;
  text-decoration: none;
}
.social-icons ul li a i {
  -webkit-transition: all 0.2s ease-in;
  -moz-transition: all 0.2s ease-in;
  -o-transition: all 0.2s ease-in;
  -ms-transition: all 0.2s ease-in;
  transition: all 0.2s ease-in;
}
.social-icons ul li a:focus i,
.social-icons ul li a:active i {
  transition: none;
  color: #222222;
}

 

Step 3- Create Components For Firebase Authentication

To manage the Firebase Authentication in Vue app, we need to create the following components. Then, we go to the src/components folder and create the following files.

  • Login.vue
  • Signup.vue
  • Home.vue
  • ForgotPassword.vue

Below is an example of Vue component:

<template>
    <div>
       <!-- Content goes here -->
    </div>
</template>
<script>
    export default {
      data() {
         return {...}
      }
    }
</script>

 

Step 4- Create Routers And Enable Navigation

In this step, we will type the below command on the terminal and press enter to install the vue-router module:

npm add vue-router@^3.1.6

Then, we will go to the src/router/index.js file and replace it with existing code:

import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
  const routes = [
  {
    path: '/',
    name: 'signup',
    component: () => import('../components/Signup.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../components/Login.vue')
  },
  {
    path: '/forgot-password',
    name: 'forgot-password',
    component: () => import('../components/ForgotPassword.vue')
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('../components/Home.vue')
  }
]
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
export default router

 

We are all set with the /signup,/login,/forgot-password and /home routes. Next, we will create a navigation header using the Bootstrap nav-bar component.

Afterward, we open the src/App.vue file and the following code:

<template>
  <div class="vue-tempalte">
    <!-- Navigation -->
    <nav class="navbar shadow bg-white rounded justify-content-between flex-nowrap flex-row fixed-top">
      <div class="container">
        <a class="navbar-brand float-left" href="https://www.positronx.io" target="_blank">
           positronX.io
        </a>
        <ul class="nav navbar-nav flex-row float-right">
          <li class="nav-item">
            <router-link class="nav-link pr-3" to="/login">Sign in</router-link>
          </li>
          <li class="nav-item">
            <router-link class="btn btn-outline-primary" to="/">Sign up</router-link>
          </li>
        </ul>
      </div>
    </nav>
    <!-- Main -->
    <div class="App">
      <div class="vertical-center">
        <div class="inner-block">
          <router-view />
        </div>
      </div>
    </div>
  </div>
</template>

 

Step 5- Set Up Firebase Project

We need to create a Firebase project to get started with Vue and Firebase Authentication. Then, we will go to console.firebase.google.com to create a Firebase project.

Here, we will click “Click a project”:

Setting up Firebase Project

Then, we click on “Continue” to generate the project.

 

project name

 

Further, we will click on the web icon:

Firebase web icon

 

Afterward, we enter the project name and click on “Next”:

 

Add Firebase app

Then, we have to take the Firebase configuration details which we will need later to connect Vue with Firebase:

 

Firebase configuration

 

Here, we will click on “Authentication”:

 

Configure Firebase Sign-in Providers

 

Here, Firebase is offering lots of authentication providers that can easily allow us to authenticate using social channels, email/password and phone numbers. We only need to enable the Email/Password auth provider:

 

configure Firebase Sign-in providers

 

Step 6- Add firebase In Vue

Here, in this step, we will install the Firebase plugin using the following command in order to add the Firebase to the Vue app:

npm add firebase@^8.10.0

 

Afterward, we need to go to the main.js file. Then, we have to import the Firebase module and add the Firebase configuration details:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import firebase from 'firebase/app';
import 'bootstrap/dist/css/bootstrap.min.css'
import '@/assets/css/main.css'
Vue.config.productionTip = false
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')

 

Step 7- User Registration With Email/Password

We are going to register a user with the name, email and password. Then, we need to open the src/components/Signup.vue file and place the following code:

<template>
    <div class="vue-tempalte">
        <form @submit.prevent="userRegistration">
            <h3>Sign Up</h3>
            <div class="form-group">
                <label>Name</label>
                <input type="text" class="form-control form-control-lg" v-model="user.name" />
            </div>
            <div class="form-group">
                <label>Email</label>
                <input type="email" class="form-control form-control-lg" v-model="user.email" />
            </div>
            <div class="form-group">
                <label>Password</label>
                <input type="password" class="form-control form-control-lg" v-model="user.password" />
            </div>
            <button type="submit" class="btn btn-dark btn-lg btn-block">
               Sign Up
            </button>
            <p class="forgot-password text-right">
                Already registered 
                <router-link :to="{name: 'login'}">sign in?</router-link>
            </p>
        </form>
    </div>
</template>

<script>
import firebase from "firebase";
export default {
  data() {
    return {
      user: {
        name: '',
        email: '',
        password: ''
      }
    };
  },
  methods: {
    userRegistration() {
      firebase
      .auth()
      .createUserWithEmailAndPassword(this.user.email, this.user.password)
      .then((res) => {
        res.user
          .updateProfile({
            displayName: this.user.name
          })
          .then(() => {
            this.$router.push('/login')
          });
      })
      .catch((error) => {
         alert(error.message);
      });
    }
  }
};
</script>

 

To create a new user account via Vue fronted with a name, email and password fields, we took the following approach.

We created a new sign-up form in Vue with Bootstrap. To register a new user, we called the createUserWithEmailAndPassword() method and passed user email and password:

 

User Registration with Email/Password

 

Step 8- Vue Firebase Login Example

Now, we will implement the user login in Vue app with Firebase API. We need to correct the email and password to access in the app. So, we have to open the src/components/Login.vue file and include the given code:

<template>
    <div class="vue-tempalte">
        <form @submit.prevent="userLogin">
            <h3>Sign In</h3>
            <div class="form-group">
                <label>Email address</label>
                <input type="email" class="form-control form-control-lg" v-model="user.email" />
            </div>
            <div class="form-group">
                <label>Password</label>
                <input type="password" class="form-control form-control-lg" v-model="user.password" />
            </div>
            <button type="submit" class="btn btn-dark btn-lg btn-block">Sign In</button>
            <p class="forgot-password text-right mt-2 mb-4">
                <router-link to="/forgot-password">Forgot password ?</router-link>
            </p>
        </form>
    </div>
</template>

<script>
import firebase from "firebase";
export default {
  data() {
    return {
      user: {   
        email: '',
        password: ''
      }
    };
  },
  methods: {
    userLogin() {
        firebase
        .auth()
        .signInWithEmailAndPassword(this.user.email, this.user.password)
        .then(() => {
            this.$router.push('/home')
        })
        .catch((error) => {
          alert(error.message);
        });
    }
  }
};
</script>

 

We are using the signInWithEmailAndPassword(email, password) method and passing the registered email address and correct password to make the user login to our Vue app.

 

Step 9- Send Password Reset Email

Now, we have to open the components/ForgotPassword.vue component and add the following code inside it:

<template>
    <div class="vue-tempalte">
        <form @submit.prevent="forgetPassword">
            <h3>Forgot Password</h3>
            <div class="form-group">
                <label>Email</label>
                <input type="email" class="form-control form-control-lg" v-model="user.email" />
            </div>
            <button type="submit" class="btn btn-dark btn-lg btn-block">Reset password</button>
        </form>
    </div>
</template>
<script>
import firebase from "firebase";
export default {
  data() {
    return {
      user: {   
        email: ''
      }
    };
  },
  methods: {
    forgetPassword() {
        firebase
        .auth()
        .sendPasswordResetEmail(this.user.email)
        .then(() => {
            alert('Check your registered email to reset the password!')
            this.user = {   
              email: ''
            }
        }).catch((error) => {
          alert(error)
        })
    }
  }
};
</script>

 

The sendPasswordResetEmail(email) method takes email id and when it is appropriately called, it sends the password reset instruction on the registered email id.

 

Step 10- User Logout And Display Logged In User Data

We are going to cover how to log out from the Firebase and Vue app and display the logged-in user’s data.

Now, we open the src/components/Home.vue file and place the given code:

<template>
    <div class="vue-tempalte">
        <h3>Welcome</h3>
           <p>{{user.displayName}}</p>
           <p>{{user.email}}</p>
        
        <button 
        type="submit" 
        class="btn btn-dark btn-lg btn-block"
        @click="logOut()">
            Log out
        </button>
    </div>
</template>
<script>
import firebase from "firebase";
export default {
  data() {
    return {
      user: null
    };
  },
  created() {
    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        this.user = user;
      } else {
        this.user = null;
      }
    });
  },
  methods: {
    logOut() {
      firebase.auth().signOut().then(() => {
        firebase.auth().onAuthStateChanged(() => {
          this.$router.push('/login')
        })
      })
    }
  }
};
</script>

 

In the given above source code, we are getting the logged-in user’s data when the auth state is changing. The auth.signOut() method logs out the user from the firebase app.

Here, we start the Vue app by using the following command:

npm run serve

 

Conclusion

In this Vue tutorial, we have learned how to add basic authentication in a Vue app using email and password via the Firebase auth provider. We also looked at how to sign up and send a password reset email via the Vue app.

 

Thanks

 

Leave a Reply

Your email address will not be published. Required fields are marked *