How to create a web app in Vue.js with Firebase, Vuex and Vue Router (Part 1)

Here we are going to implement a showcase application with firebase backend. We will be using the Vuetify, Vuex and Vue-Router and Firebase.

What we will be doing

  1. Create Vue.js application
  2. Add vuetify
  3. Create a structure for our app
  4. Workflow of our app
  5. Create a firebase account
  6. Link the firebase to the app
  7. Create a Navigation Bar to the app
  8. Add Register Page
  9. Test Registration using firebase
  10. Add Login Page
  11. Test login using firebase
  12. Integrate vuex
  13. Refactor the Register.vue file
  14. Refactor the Signin.vue file
  15. Fix the Navigation issues in Sign in and Logout

1. Create Vue.js application

For that, I have used the vue-cli for that. It has some nice features by which we can select all the features on creating the Vue.js application. They also provide some option to save the configs as a preset so that we can use the same when creating new applications. Hereby default when used the vue-cli , it will install and configure the vuex and vue-router too.

vue create showcase

Hooray, the first step is completed, now need to run the local development using

npm run serve

Our application is running on port 8080.

2. Add vuetify

Vuetify is a material design framework for Vue.js and it simplifies implementing our application needs. We are going to use that too. Since we are using the vue-cli, we can easily add the vuetify to our app using the command,

vue add vuetify

Now run development server, to see the magic of vuetify.

Awesome, vuetify integrated to our app

3. Create a structure for our app

Currently, our application is structure is like this.

We are doing some tweaks to our application to contain some changes. The structure is based on some use cases and some general ideas in other blogs too. It may be offending to some too. Feel free to use your own project structure if you have.

This will be our proposed plan for the application. The auth folder will contain the register and login components.

The services folder will contain any API call or data needs to be added.

The helper's folder will help for any guards like authentication is needed to view any page.

Rest of the folder structure is self-explanatory I believe.

5. Create a firebase account

Before diving into firebase, one needs to understand why firebase. First of all, it is a product of google quoting their words

Firebase gives you functionality like analytics, databases, messaging and crash reporting so you can move quickly and focus on your users.

In our application, will be focussing on the authentication, and database functionalities only.

link for firebase

We can use our Gmail to log in to firebase console. On the top right corner, we have the “Goto console” will redirect to the app section.

I have already an app running with firebase. Click on the Add project link and add your project name also,

Yes, our project is ready to run in firebase.

Since we are authenticated using firebase, we need to configure some points in firebase.

Click on authentication -> setup sign-in method.

I am currently enrolling with email password scenario, so we are enabling that only.

Now, we need to link our app with firebase, this can be done using the configs which are available when clicking on the web setup,

Copy the configs, we need to add the configs to the Vue.js app soon.

6. Link the firebase to the app

So far, we have created a firebase app, now we need to link to our Vue.js app. To do that we need some steps

  1. Add env implementation.
  2. Install firebase.
  3. Add the firebase keys to the app.

1. Add env implementation.

This is an important part for me and everyone. We have created a firebase app and firebase has given us some credentials. We can’t blindly add to our app. It is not an issue, others might use our credentials. So it will be good to keep those in our .env file

Below points need to be in mind before doing this.

a. Create a .env file in the root path of our app, which will contain all the details which are needed when our app running on every mode.

b. Create a .env.development file which will contain all the details which are needed for our app to be executed in locally. We are keeping our firebase credentials in here.

c. All the env variables should be begins with “VUE_APP_” . or else they are discarded.

d. Make sure to restart the app after adding those file. For me, it is working only after restart.

I just added a test heading to make sure it is working in the .env file. This will be used for every mode in our app.

VUE_APP_TITLE='SHOW CASE'

Now, the code becomes,

Will give show case as a link

2. Install firebase

To use firebase in our app, need to install the firebase to our app.

npm install firebase --save

3. Add the firebase keys to the app.

Now we can copy the firebase key to our app. we can use the .env.development file and main.js for this.

Copy the configs from firebase and add those to our main.js file in environmental variables.

All the keys are now changed with ENV variables, they are replaced with original values from a .env.development file.

Import firebase to the main.js file as well, the total code in the main.js becomes,

import Vue from 'vue'
import './plugins/vuetify'
import App from '@/App.vue'
import router from '@/router'
import store from '@/store'
import * as firebase from 'firebase'
Vue.config.productionTip = falsenew Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
var config = {
apiKey: process.env.VUE_APP_FIREBASE_API_KEY,
authDomain: process.env.VUE_APP_FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.VUE_APP_FIREBASE_DATASE_URL,
projectId: process.env.VUE_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.VUE_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.VUE_APP_FIREBASE_MESSAGE_SENDER_ID
}
firebase.initializeApp(config)

7. Create a Navigation Bar to the app

We have a navigation bar currently, but we are moving all the code related to the navigation as a separate component called NavBar.vue. We are creating an option to register, sign in and sign out button in the navbar currently. To do that

Import the nav-bar component to the App.vue and define the component in App.vue.

<template>
<v-app>
<!-- display nav bar -->
<nav-bar></nav-bar>
</v-app>
</template>
<script>
import NavBar from '@/views/NavBar'
export default {
name: 'App',
components: {
NavBar
}
}
</script>

The important takeaway here is that, once we declare a component as a child one then we can use the component using the same name as we are declared.

here NavBar === <nav-bar>

8. Add Register Page

Now it is the time of the registration page. We need to create a component in components/auth/Register.vue

I am adding some validations in the forms like email is mandatory, display hidden password once click on the icon disable the register button when invalid data is given. These are all I found out from the vuetify . You check out for more information.

In order to display the register page, we have already added a link in the navigation bar, now we need to link that to our component and need to display the component. Which can be easily executed using the vue-router.

For that,

  1. Import the component to the router/index.js file
  2. Set the path and component in router/index.js file.
  3. Set the link in the navigation bar.
  4. Display the component using <router-view> in App.vue

1. Import the component to the router/index.js file

import Register from '@/components/auth/Register.vue'

2. Set the path and component in router/index.js file.

routes: [
{
path: '/register',
name: 'Register',
component: Register
}
]

3. Set the link in the navigation bar.

This is already we done, I just added here to understand,

{
title: 'Register',
icon: 'face',
link: '/register'
},

4. Display the component using <router-view> in App.vue

<router-view></router-view>

That’s all, now we can see the registration page.

commit link for the change

9. Test Registration using firebase

It is now time for real play. I am adding some firebase registration module to the Register.vue. We will use vuex after this. Currently, we are checking to make sure that it is working.

We have an existing method called validate in the register page. we are adding firebase module to that method or we can create a separate method and call that from the validate. Also, need to import the firebase to the Register.vue as well.

firebase module for registration

registerWithFirebase () {
firebase.auth().createUserWithEmailAndPassword(this.email, this.password)
.then((response) => {
alert('success')
console.log(response)
})
.catch((error) => {
alert('failure')
console.log(error)
})
}

Call this method in the validate() using

this.registerWithFirebase()

We got our success!!!

Now check the firebase it is updated there,

10. Add Login Page

The changes here is also the same as that of Registration page.

  1. Add login code in the auth/Signin.vue
  2. Import the auth/Signin.vue to router file.
  3. Add the routes in the router file.

We have a page is coming as login,

commit link for the code change

11. Test login using firebase

We are adding the login module to the Signin.vue currently. Once the vuex is completed, will move to there. we are creating a new method and call this method in the validate() as well. Also, need to import the firebase here also,

  1. Import firebase to the Signin.vue
  2. Add the firebase login module to the new method.
loginWithFirebase () {
firebase.auth().signInWithEmailAndPassword(this.email, this.password)
.then((response) => {
alert('success')
console.log(response)
})
.catch((error) => {
alert('failure')
console.log(error)
})
}

3. Call the firebase login method inside the validate method


this.loginWithFirebase()

4. Test the successful login

5. Test the failure login

console output

12. Integrate vuex

Now it is the most important part, state management with vuex. We need to write most of the code currently we have. Before dive into that, need to have a clear idea of what we are going to save currently.

If you have no idea how the vuex works, Please go through one of my earlier blog about this,

Link for the vuex blog

So far, we have created a sign-up and sign in in corresponding vue files. Now we are moving that code to the store/index.js

1. state available in vuex

The state in the vuex will be shared among all the components. So once a component updated the state, it will be affected all the other components which are using this state.

We have user state, which will keep the user-id from the firebase once a user is signed or signup

We have a status state, which will point whether the login or signup success or not.

We have error state, which will keep any error when using firebase, will be displaying those error in future.

2. Mutations in vuex

If we want to change the state need to use the mutations as well. Here we are using,

setUser() will set the user we got from the firebase

removeUser() will remove the user-id from the state.

setStatus() change the status.

setError() set the error status or remove the error from the state

3. Actions in vuex

It is the mutations that are alone needed to change the state but sometimes an async operation is done, will be using the actions.

Mutations are good for sync actions only. Actions will, in turn, call the mutations also.

We can remove the code from the vue files and call the actions from there.

4. getters in vuex

In order to display some data based on the state, which can be done using the getters,

Last but not least,

import the firebase to the store/index.js.

13. Refactor the Register.vue file

We have now a store in place, we can easily remove the firebase signup module from the Register.vue file.

We can remove the import firebase in the Register.vue file and the registerWithFirebase() becomes,

registerWithFirebase () {
const user = {
email: this.email,
password: this.password
}
this.$store.dispatch('signUpAction', user)
}

the code “this.$store.dispatch(‘signUpAction’, user)” will call the state and update the details,

Now run the register and check the vuex using the vue-devlopement tools.

After registration, we got success and vuex is updated also,

14. Refactor the Signin.vue file

Here, also we applied the logic for Register.vue file. The code becomes,

loginWithFirebase () {
const user = {
email: this.email,
password: this.password
}
this.$store.dispatch('signInAction', user)
}

The Output is,

15. Fix the Navigation issues in Sign in and Logout.

Currently, we are displaying all the links, need to fix that also. Need to implement the logout button also.

  1. Display the login and register only if the user is not signed in
  2. Display the logout if the user is signed in.
  3. Implement the logout.

1. Display the login and register only if the user is not signed in

For that, we can use the help of the store, We can check that if the state has user is null then we need to display those. I will be using the computed property for that.

userLogedIn () {
return this.$store.getters.user
}

it will call the store getters and link the result to the navbar with v-if

<v-toolbar-items class='hidden-xs-only' v-if="!userLogedIn">
...
</v-toolbar-items>

2. Display the logout if the user is signed in.

We can use the same method used for register and login. But just v-else

v-toolbar-items class='hidden-xs-only' v-else>
<v-btn>
...
</v-btn>
</v-toolbar-items>

3. Implement the logout.

Need to add firebase signout functionality to the store action and update the other state as well,

signOutAction ( {commit}) {
firebase.auth().signOut()
.then((response) => {
commit('setUser', null)
commit('setStatus', 'success')
commit('setError', null)
})
.catch((error) => {
commit('setStatus', 'failure')
commit('setError', error.message)
})
}

Now, we need to add a signout method which will call the store action once a click happened, this can be achieved by,

@click='logoutFromFirebase'

in the NavBar.vue,

methods: {
logoutFromFirebase () {
this.$store.dispatch('signOutAction')
}
}

and the signout completed,

I know, there is a lot of pending works, needed to be completed, but here we completed only the signup and sign in functionality, Will the auto sign in when the page refreshed, redirect to new page once authenticated, clear the form fields, authenticated from unwanted page attacks, display error message from firebase etc, all those will be covered in the next Part.

As I promised, the link for the GitHub repo.

Please comment or clap if you find this useful.

JavaScript in Plain English

Learn the web's most important programming language.

Anoob Bava

Written by

#believer, seraching for Happy path Scenario, #githublover

JavaScript in Plain English

Learn the web's most important programming language.