Vue 2 Tutorial- Firebase Authentication Tutorial Example

Firebase Integration Authentication in Vue.js 2 application; In this tutorial, we will learn how to integrate firebase authentication in a Vue app. In addition, we will also learn to register a user, login a user and send password reset mail and logout from the firebase app using the Vue.js app.

We will use the firebase database to add authentication to the Vue project from scratch. Firebase is a robust real-time database that offers backend-as-a-service.

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

 

See below the contents that we will cover in this Vue guide:

  • Install and Setup Vue Project
  • Add Bootstrap & Global CSS In Vue
  • Create Components For Firebase Authentication
  • Create Routers And Enable Navigation
  • Set Up Firebase Project
  • Add Firebase In Vue
  • User Registration With Email/Password
  • Vue Firebase Login Example
  • Send Password Reset Email
  • User Logout And Display Logged in User Data
  • Conclusion

 

Step 1- Install And Setup Vue Project

Vue CLI makes the Vue app development very smooth. We simply have to run the following command in order to install it on our device:

# npm
npm install -g @vue/cli

 

We will use the below command to create a new Vue project and get inside of it:

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, we have to 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"
},

 

Step 2- Add Bootstrap & Global CSS In Vue

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

npm install bootstrap

Further, we need to open 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')

 

Then, we have to include global styling in Vue app for which we create the src/assets/css folder , then we will create the main.css file.

Now, we 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')

 

Here, we will add the given code in the assets/css/main.js 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

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

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

Following 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 following command and press enter to install the vue-router module:

npm add vue-router@^3.1.6

 

Further, we need to go to the src/router/index.js file and replace it with the 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 after which we will create a navigation header using the Bootstrap navbar component.

Then, we have to open the src/App.vue file and add the given 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

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

Then, we click “create 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 *