FIREBASE - ReferenceError: Cannot access 'auth' before initialization

Viewed 484

i'm in the middle to learn Auth with Firebase using NextJS, tryin to understand using multiple source (article / youtube) but i'm stuck with this error

ReferenceError: Cannot access 'auth' before initialization

Honestly i'm still tryin to find the source but still stuck

Here's my firebase.js

import { firebase, initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
const firebaseConfig = {
  apiKey: process.env.APIKEY,
  authDomain: process.env.AUTH,
  projectId: process.env.PID,
  storageBucket: process.env.BUCKET,
  messagingSenderId: process.env.MSID,
  appId: process.env.AID,
  measurementId: process.env.MID,
};
const app = !firebase.apps.length
  ? initializeApp(firebaseConfig)
  : firebase.app();
const analytics = getAnalytics(app);
const auth = app.auth();
const db = app.firestore();
const googleProvider = new firebase.auth.GoogleAuthProvider();

export {
  auth,
  db,
  signInWithGoogle,
  ...
};

and this is my login.js page

import React, { useEffect, useState } from "react";
import {
  auth,
  signInWithEmailAndPassword,
  signInWithGoogle,
} from "../../firebase/index";
import Link from "next/link";
import { useAuthState } from "react-firebase-hooks/auth";
function Login() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [user, loading, error] = useAuthState(auth);
  useEffect(() => {
    if (loading) {
      // maybe trigger a loading screen
      return;
    }
    if (user) {
      alert("GET USER");
      console.log(user);
    }
  }, [user, loading]);
  return (
  ...

I'm using

"firebase": "^9.6.1",
"firebase-admin": "^10.0.1",

am i doing something wrong? or am i missing something? please help:(

2 Answers

First of all, you are using the legacy version of firebase I recommend you to use newer versions (9.9.2 atm). About your problem ; it seems like you need to call getAuth() or initializeAuth() functions before try to get instance of auth.

You must import getAuth() from Firebase Auth SDK and then initialize it as shown below:

import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";
import { getAnalytics } from "firebase/analytics";

const firebaseConfig = {...};

const app = initializeApp(firebaseConfig)

const analytics = getAnalytics(app);
const auth = getAuth(app);
const db = getFirestore(app);

export {
  auth,
  db,
};

You don't need to check if Firebase has already been initialized when using Modular SDK.

Related