Home > Software engineering >  Error when trying to redirect user to another page if not authenticated in Firebase
Error when trying to redirect user to another page if not authenticated in Firebase

Time:11-12

I'm getting this error.

TypeError: Cannot read properties of undefined (reading '$router')

I supposed it's because I didn't import anything related to router in my file, but I'm thinking that it's strange cause I did the same in other pages and this error didn't happened.

firebase.js

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import { getAuth, onAuthStateChanged } from "firebase/auth";

// Your web app's Firebase configuration
export const firebaseConfig = {
  apiKey: process.env.API_KEY,
  authDomain: process.env.AUTH_DOMAIN,
  projectId: process.env.PROJECT_ID,
  storageBucket: process.env.STORAGE_BUCKET,
  messagingSenderId: process.env.MESSAGING_SENDER_ID,
  appId: process.env.APP_ID,
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const auth = getAuth(initializeApp(firebaseConfig));

const authenticator = getAuth();
onAuthStateChanged(authenticator, (user) => {
  if (user) {
    const uid = user.uid;
    console.log(user);
  } else {
    this.$router.push("/");
  }
});

const db = getFirestore(app);
export default db;

This is my page to add an event where I did the same thing as above and it worked

AddEvent.vue

... 
  else {
    const docRef = await addDoc(collection(db, "eventos"), novoEvento);
    this.$q.notify({
      color: 'teal',
      textColor: 'white',
      icon: 'thumb_up',
      message: 'Event created!',
      position: 'top-right',
    })
    this.$router.push("/");
  }

I didn't import anything related to route or router in that page on Vue to that work, so how am I supposed to do that import on the firebase.js file?

CodePudding user response:

You didn't post your main.js, but typically, in a Vue app, the router is injected into the Vue app using Vue.use(router) or something similar. Because of this, the $router variable is injected into all Vue components and you can access the variable using the this.$router syntax.

Your firebase.js file is not a Vue component and therefore there was no $router injected into it. You'll need to access your router object by importing it directly from where it is defined instead.

  • Related