Ad

Firebase Not Initialized In Vue3 Router

- 1 answer

I initialize firebase in main.js and it works overall in the application.

When I use a firebase in the router for the beforeEnter checks it doesn't recognize that firebase has been initialized.

exception: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).

Looking at logs, the router beforeEnter check is done before main.js where the init is done.

main.js:

firebase.initializeApp(firebaseConfig);
firebase.auth().onAuthStateChanged(function(user){...}

router.ts:

router.beforeEach((to, from, next) => {
  console.log("router | beforeEach")
  const currentUser = firebase.auth().currentUser;
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth);

  if(requiresAuth && (!currentUser || currentUser.isAnonymous)) next('login')
  else if(!requiresAuth && currentUser) next('eorDashboard')
  else next();
})

How to bypass this issue as it was working well in Vue2?

Ad

Answer

In your main.js, you should make sure only init Vue application when Firebase Auth object is ready to use

main.js

let app = ''

firebase.initializeApp(firebaseConfig);
firebase.auth().onAuthStateChanged(() => {
  if (!app) {
    app = new Vue({
      router,
      render: h => h(App)
    }).$mount('#app')
  }
})
Ad
source: stackoverflow.com
Ad