Building a VueJS App with Firebase Hosting and Validation

Building a VueJS App with Firebase Hosting and Validation
This guide is proof as to how easy it is to set up a back-end service to register and authenticate users via Firebase. These features can be used for both Web and Mobile applications, drastically reducing the effort required to build applications.

Most Businesses prefer to use impressive front-end applications with responsive User Interfaces (UI). These front-end apps are nothing more than nice UIs, without a robust back-end service. With the introduction of virtualization and cloud technologies, we have access to many services like SaaS, PaaS, IaaS. Irrespective of the size of an organization, a good app can greatly enhance its business.

Firebase is one such cloud-based BaaS platform that provides database, cloud storage, cloud messaging, and remote configuration. All these aspects can easily be leveraged when building a successful mobile app, just by creating the UI and linking it to Firebase using their configuration. Firebase allows you to store data in databases and cloud storage. You can send notifications and messages using Cloud Messaging and use Remote Config to perform A/B testing.

Cloud “Backends” with Cloud Component Hubs

We are in an exciting period in the history of web development. This combination of cloud component hubs likeBit.dev (that allow you to publish and organize reusable components in the cloud) and cloud solutions like Firebase, shift our attention, as developers, from high-resolution implementations to semi-abstract compositions.

Setting up the Vue project

Let’s start by setting up a Vue project with three views: register, login, and home.

  1. We will log in to the application using Firebase’s authentication feature.

  2. If the authentication attempt is rejected, you can register and try to login again.

  3. We’ll check if Firebase validates email and user names.

Vue Project

We’ll use Vue CLI to create a new Vue project. Install CLI by using the following command.

npm install -g @vue/cli

command.txt

Next, create the Vue project,

vue create Vuefirebase-auth

command.txt

Creating Login.vue:

First, we’ll create a simple login view to login using email and password. Currently, we’ll just have two inputs and a button to log in.

<template>
  <div class="login">
    <h2>Login</h2>
    <input type="text" v-model="email" placeholder="Email"><br>
    <input type="password" v-model="password" placeholder="Password"><br>
    <button @click="login">Sign in</button>
  </div>
</template>

login.vue

As we create our first component, we’ll now display it in our application. As you install Vue using the CLI, you will see an option to install vue-router. If you haven’t already installed the vue-router, you can do so with the following command.

npm install vue-router

command.txt

Vue-router is used with Vue to create a Single Page Application. It integrates well with Vue core components by mapping routes with views. Let’s integrate this view into the router.js file.

import Vue from "vue";
import Router from "vue-router";
import Login from "./Components/Login";
 
Vue.use(Router);
 
const router = new Router({
  routes: [
    {
      path: "*",
      redirect: "/login"
    },
    {
      path: "/",
      redirect: "/login"
    },
    {
      path: "/login",
      name: "Login",
      component: Login
    }
  ]
});
 
export default router;

router.js

Currently, we just have a login component without any styling. That’s what we’ll be adding next:

<style scoped>
/* "scoped" attribute limit the CSS to this component only */
.login {
  margin-top: 50px;
}
input {
  width: 40%;
  padding: 20px;
  margin: 20px 0;
}
button {
  width: 10%;
  margin-top: 30px;
  padding: 20px;
  cursor: pointer;
}
p {
  margin-top: 50px;
  font-size: 16px;
}
p a {
  cursor: pointer;
}
</style>

login.vue

Changing App.vue:

The main component renders app.vue first. We modify this file to have . A component of router “router view” renders the path to “/login”, defined in the /router.js.

<template>
  <div id="app">
    <router-view/>
  </div>
</template>
 
<script>
  export default {};
</script>

App.vue
Browse to http://localhost:8080/#/login, and you will get the below image.

This is image title

Create Register.vue:

Let’s create a Register view to accommodate new users.

<template>
  <div class="register">
    <p>Register</p>
    <input type="text" v-model="email" placeholder="Email">
    <br>
    <input type="password" v-model="password" placeholder="Password">
    <br>
    <button @click="signUp">Register</button>
    <span><router-link to="/login">login</router-link>.
    </span>
  </div>
</template>

Register.vue
Add the following styling rules to Register.vue

<style scoped>
.register {
  margin-top: 40px;
}
input {
  width: 40%;
  padding: 20px;
  margin: 20px 0;
}
button {
  width: 10%;
  margin-top: 30px;
  padding: 20px;
  cursor: pointer;
}
span {
  display: block;
  margin-top: 20px;
  font-size: 11px;
}
</style>

Register.vue

Set Navigation

Since we have created two of the views, let’s setup the navigation between them. The vue-router gives us a component called “router-link” that helps us navigate between views. Add these links below the button element.

<p>
      <router-link to="/register">Register</router-link>
</p>
<span><router-link to="/login">login</router-link>.

login.vue

<span>
	<router-link to="/login">login</router-link>
</span>

Register.vue

These links will allow users to navigate between the Login and Register pages.

Create Home.vue:

Once a user logs in, we’ll be displaying a Home page to users. The code given below is for a simple Home.vue page with a sign-out button.

<template>
  <div class="home">
    <HelloWorld msg="Firebase Auth Vue App"/>
    <button @click="SignOut">Sign Out</button>
  </div>
</template>

Home.vue

Now let’s set up the click event for the Sign-in button so that the user is authenticated when the button is clicked.

<template>
	…
		<button @click="login">Sign in</button>
	…
</template>
<script>
…
    login: function() {
	     this.$router.replace("home");
       }
    }
 …
</script>

Login.vue
To use the router using “this.”, ensure that the router is injected into your main.js file?.

import router from "./router";
 
 
// handle page reloads
new Vue({
  router,
  render: h => h(App)
}).$mount("#app");

main.js

Now that the views are created, let’s add the routes for the Register and Home views.

  {
      path: "/home",
      name: "Home",
      component: Home,
   },
    {
      path: "/login",
      name: "Login",
      component: Login
    },
    {
      path: "/sign-up",
      name: "SignUp",
      component: SignUp
    }

router.js

We have now completed the UI aspects of the Login, Register, and Home views. Users will be able to go to the Home page by clicking the Sign in button. Now let’s set up the Firebase database to store the login credentials of our users.

Setting up Firebase:

To create a Firebase project as a back-end for your apps, go to the Firebase website and create an account.

This is image title

In the Firebase console, click on “add project”, give the name for your project, and click the “Web” icon to add Firebase to the web application.

This is image title

  1. Select Web app

This is image title
3 Add Firebase to your web app

This is image title
4. Select Authentication and select “Set up sign-in method”

Once you create the project, you will be provided with the configuration details of your Firebase account so that it can be connected with your application. Copy this code for later use.

Click “Authentication” in the main navigation menu (left) of the Firebase dashboard. In the “Sign-in method” tab, select “Email/Password”, enable it, and click “Save”.
This is image title
5. Allow users to sign-up using email and password.

Next, select “Database” in the main navigation menu (left) and select the “Start in test mode” option to enable read and write privileges to the database.

This is image title
6 Create the database in test mode
Now select the location in which you want the Firebase service to be hosted. Note that this setting cannot be changed once the service is setup.

This is image title

  1. Set the Firestore Location

Install Firebase in Vue project:

Now that the Firebase account has been created, let’s install Firebase in our project using the command line.

npm i firebase

command.txt
To connect to the firebase db, we’ll be using the configuration information provided by Firebase earlier. The configuration code will look like the following sample code:

const firebaseConfig = {
	  apiKey: "***",
  authDomain: "***",
  databaseURL: "***",
  projectId: "***",
  storageBucket: "***",
  messagingSenderId: "***",
  appId: "***"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);

config.js

Now, update the main.js file to authenticate users through Firebase. Below is the complete main.js file. Add the Firebase configurations here:

import Vue from "vue";
import App from "./App.vue";
import router from "./router";
 
import "./assets/scss/app.scss";
import firebase from "firebase";
 
Vue.config.productionTip = false;
 
var firebaseConfig = {
  apiKey: "***",
  authDomain: "***",
  databaseURL: "***",
  projectId: "***",
  storageBucket: "***",
  messagingSenderId: "***",
  appId: "***"
};
// Initialize Firebase
 
firebase.initializeApp(firebaseConfig);
 
// handle page reloads
new Vue({
  router,
  render: h => h(App)
}).$mount("#app");

main.js

For production apps, the config details are added in a separate file and referred to in the main file.

Register Users through the UI:

Now let’s change the Register page so that users can easily register through the UI.

return {
      email: "",
      password: ""
    };

Register.vue

Once the user enters their username (email) and password, we can use the Firebase .auth() method “.createUserWithEmailAndPasswod()” to perform the authentication. Below is the block of the Register page.

<script>
import firebase from "firebase";
export default {
  name: "Register",
  data() {
    return {
      email: "",
      password: ""
    };
  },
  methods: {
    Register: function() {
      firebase
        .auth()
        .createUserWithEmailAndPassword(this.email, this.password)
        .then(
          user => {
            this.$router.replace("home");
          },
          err => {
            alert(err.message);
          }
        );
    }
  }
};
</script>

Register.vue

As we create users, the “.createUserWithEmailAndPassword” method validates through Firebase for the sign-in provider of the Auth section.

We can now register users as the required configurations are done in Firebase.

Logging in through the UI:

We now need to allow registered users to Login and direct them to the Home page if their credentials are valid. To perform a login, we’ll use the “.signInWithEmailAndPassword” method of Firebase auth(), as follows:

Display Home page after Authentication:

Only authenticated users should be redirected to the Home page. So we need to restrict access to the Home page through the “requireAuth” meta field of the vue-router. This is done as follows:

<template>
  <div class="login">
    <h2>Login</h2>
    <input type="text" v-model="email" placeholder="Email">
    <br>
    <input type="password" v-model="password" placeholder="Password">
    <br>
    <button @click="login">Sign in</button>
    <p>
      <router-link to="/register">Register</router-link>
    </p>
  </div>
</template>
 
<script>
import firebase from "firebase";
export default {
  name: "login",
  data() {
    return {
      email: "",
      password: ""
    };
  },
  methods: {
    login: function() {
      firebase
        .auth()
        .signInWithEmailAndPassword(this.email, this.password)
        .then(
          user => {
            this.$router.replace("home");
          },
          err => {
            alert("Oops. " + err.message);
          }
        );
    }
  }
};
</script>
 
<style scoped>
/* "scoped" attribute limit the CSS to this component only */
.login {
  margin-top: 50px;
}
input {
  width: 40%;
  padding: 20px;
  margin: 20px 0;
}
button {
  width: 10%;
  margin-top: 30px;
  padding: 20px;
  cursor: pointer;
}
p {
  margin-top: 50px;
  font-size: 16px;
}
p a {
  cursor: pointer;
}
</style>

Login.vue

Validation of Email and Password:

const router = new Router({
  routes: [
    {
      path: "*",
      redirect: "/login"
    },
    {
      path: "/",
      redirect: "/login"
    },
    {
      path: "/home",
      name: "Home",
      component: Home,
      meta: {
        requiresAuth: true
      }
    },
    { 
      path: "/login",
      name: "Login",
      component: Login
    },
    {
      path: "/sign-up",
      name: "SignUp",
      component: SignUp
    }
  ]
});

router.js

As a user tries to register or login, Firebase validates their credentials to ensure that the username is in email format and that both the email and password are valid. For the purpose of this guide, we have simply displayed the error returned by Firebase during a failed registration and login requests.

user => {
	this.$router.replace("home");
},
err => {
	alert(err.message);
}

Register.vue

You will now be able to register on the application and log in.

This is image title
A record is created in Firebase upon successful authentication:

This is image title

Conclusion

This guide is proof as to how easy it is to set up a back-end service to register and authenticate users via Firebase. These features can be used for both Web and Mobile applications, drastically reducing the effort required to build applications.

This guide only covers the fundamental aspects of this process. However, Firebase provides many more features and configurations to enhance the registration and authentication processes and make them more secure.

Suggest:

JavaScript Programming Tutorial Full Course for Beginners

Learn JavaScript - Become a Zero to Hero

Top 10 JavaScript Questions

E-Commerce JavaScript Tutorial - Shopping Cart from Scratch

JavaScript Substring Method in 5 Minutes

Javascript Project Tutorial: Budget App