How to use Firebase Authentication with Vue Router?

How to use Firebase Authentication with Vue Router?

With Vue Router you might want to guard som paths and redirect users to a signup page if they are not authenticated. In this tutorial, you'll learn how to use Firebase Authentication with Vue Router

With Vue Router you might want to guard som paths and redirect users to a signup page if they are not authenticated. I will show you how this is done correctly with Firebase Authentication.

This article assumes you already have implemented your project with Vue Router and Firebase Authentication.

First, we must mark each route that we want to guard with a meta property called requiresAuth.

const routes = [  
  {    
    path: '/signin',
    name: 'signin',
    component: () => import('../views/SignIn.vue')  },
  {
    path: '/profile',
    name: 'profile',
    component: () => import('../views/Profile.vue'),
    meta: {
      requiresAuth: true
    }
  }
]

In this example, the path /signin is allowed for everyone, but /profile should only be for signed-in users.

Now we can use the beforeEach guard to check for this property.

router.beforeEach(async (to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
  if (requiresAuth && !currentUser){
    next('signin');
  }else{
    next();  
  }
});

Now if the currentUser is null or undefined, we should redirect users to the signin path. But how do we get currentUser? We can’t use firebase.auth().currentUser because on page refresh that property has not been set yet before the guard is triggered. We will have to use the onAuthStateChanged callback somehow. Let’s add a method to the firebase object after we initialize the firebase app.

firebase.initializeApp(firebaseConfig);

firebase.getCurrentUser = () => {
  return new Promise((resolve, reject) => {
    const unsubscribe = firebase.auth().onAuthStateChanged(user => {
      unsubscribe();
      resolve(user);
    }, reject);
  }
)};

This method will return a Promise which resolves currentUser as soon as it is set. onAuthStateChangedwill trigger the callback immediately with either null or the user object if signed in. Then we unsubscribe to not listen for further changes.

Now we will update our beforeEach guard so that only paths that require authentication await this method.

router.beforeEach(async (to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
  if (requiresAuth && !await firebase.getCurrentUser()){
    next('signin');
  }else{
    next();
  }
});

That’s all. This also simplifies getting the currentUser for components under the guarded routes, because we know firebase.auth().currentUser is set.

For full example check out this GitHub repository and live demo.

vuejs Firebase security

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

What is firebase,firebase bangla tutorial.

LIKE | COMMENT | SHARE | SUBSCRIBE The Firebase Realtime Database is a cloud-hosted NoSQL database that lets you store and sync data between your users in re...

Best Custom Web & Mobile App Development Company

Top Web & Mobile Application Development Company in India & USA. We specialize in Golang, Ruby on Rails, Symfony, Laravel PHP, Python, Angular, Mobile Apps, Blockchain, & Chatbots

Firebase Introduction with C#

LIKE | COMMENT | SHARE | SUBSCRIBE Firebase is a mobile and web application development platform developed by Firebase, Inc. in 2011, then acquired by Google...

Create database into firebase

LIKE | COMMENT | SHARE | SUBSCRIBE In this video, I will show you how to Create database into #firebase console. Subscribe & Stay Connected! Thank You! ♥ #Fi...

Save Employee into firebase

LIKE | COMMENT | SHARE | SUBSCRIBE In this video, I will show you how to save employee information into firebase database. Subscribe & Stay Connected! Thank ...