Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FIREBASE - ReferenceError: Cannot access 'auth' before initialization

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:(

like image 917
Haksatrya Bhaswara Avatar asked Aug 07 '26 09:08

Haksatrya Bhaswara


1 Answers

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.

like image 167
Dharmaraj Avatar answered Aug 10 '26 11:08

Dharmaraj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!