skip to Main Content

I have created a Next.js application and am using Firebase authentication. I have used the useContext hook for managing user state across my application.
The code for the AuthContext is as follows:

auth.js

import { createContext, useState, useEffect, useContext } from "react";
import { getAuth, onIdTokenChanged } from "firebase/auth";

const AuthContext = createContext({});

export const AuthProvider = ({children}) => {
    
    const auth = getAuth();
    const [user, setUser] = useState(null);

    useEffect(() => {
        return(onIdTokenChanged(auth, (user) => {
            if(user) {
                setUser(user);
            } else {
                setUser(null);
            }
        }))
    },[]);

    return(<AuthContext.Provider value={{user}}>{children}</AuthContext.Provider>);
}

export const useAuth = () => useContext(AuthContext);

However, I’m getting the following error in the auth.js file:
enter image description here

  1. I am not able to understand how to fix it.
  2. Also, I want to know if using useContext() hook is better for route protection as opposed to storing user session cookies in the browser and verifying it from there.

Edit:
I have configured Firebase in firebaseConfig.js. The code for it is as follows:

firebaseConfig.js

import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";


const firebaseConfig = {
    apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
    authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
    projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
    storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
    messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
    appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
};

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

8

Answers


  1. I was just getting the same error, I managed to fix this by doing:

    import { initializeApp } from 'firebase/app';
    import { getAuth } from "firebase/auth";
    import { getFirestore } from "firebase/firestore";
    
    const firebaseConfig{
    ...
    }
    

    And adding these lines like that:

    const app = initializeApp(firebaseConfig);
    const auth = getAuth(app);
    const db = getFirestore();
    
    export { auth, db };
    
    Login or Signup to reply.
  2. Initialize app like Marcos Oliveira said, with error handling:

    try
    {
        const app = initializeApp(firebaseConfig);
        const auth = getAuth(app);
    } catch(error) {
        console.log('Error:', error)
    }
    
    Login or Signup to reply.
  3. you just need to export firebase conifgurations as app or any other type and re import it inside the page you are working on.
    for me it was like this

       `import { getAuth,signInWithEmailAndPassword } from "firebase/auth";
       import { useState } from "react";
       import { useNavigate } from "react-router-dom";
       function SignInPage(){
       const auth=getAuth();
       const SignIn=()=>{
       signInWithEmailAndPassword(auth,email,password)
       .then((userCredentials)=>{
       const user =userCredentials.user;
       console.log(user);
       alert("successfully loged a user")
       })
       .catch((error)=>{
       const errorCode=error.code;
       const errorMessage=error.message;
       alert(errorCode,errorMessage);
       });
       }
       const [email,setEmail]=useState("")
       const [password,setPassword]=useState("")
       return(
       <div className="main">
       <input type={"email"} placeholder="Email" onChange= 
       {(e)=>setEmail(e.target.value)}/>
       <input type={"password"} placeholder="Password" onChange= 
       {(e)=>setPassword(e.target.value)}/>
       <button onClick={()=>SignIn(email,password)}>Create Account</button>
       </div>
       )}
       export default SignInPage;`   
    
    Login or Signup to reply.
  4. For anyone still dealing with this issue, my solution was to re-order my imports in the App.js.

    For some reason, the components I imported needed to be in a specific order. Otherwise, the same error is thrown.

    Login or Signup to reply.
  5. I did solve the problem by:
    first I created a firebaseConfig.js file and put my configs and exported auth

    import { initializeApp } from "firebase/app";
    import { getAuth } from "firebase/auth";
    
    const firebaseConfig = {
      apiKey: "AIzaSyAzlY091r0Ihxxxxxx5F8",
      authDomain: "mealxxxxxc.firebaseapp.com",
      projectId: "mealxxxxxc",
      storageBucket: "meaxxxxxpot.com",
      messagingSenderId: "10xxxx00",
      appId: "1:1092909165400:web:532xxxxx32d",
    };
    
    const app = initializeApp(firebaseConfig);
    
    export const auth = getAuth(app);

    then in authContext.js, I imported auth from firebaseConfig.js

    import React, { useState, createContext } from "react";
    import { signInWithEmailAndPassword } from "firebase/auth";
    import { auth } from "../firebaseConfig";
    export const AuthenticationContext = createContext();
    export const AuthenticationContextProvider = ({ children }) => {
      const [isLoading, setIsLoading] = useState(false);
      const [error, setError] = useState(null);
      const [user, setUser] = useState(null);
    
      const onLogin = (email, password) => {
        setIsLoading(true);
        signInWithEmailAndPassword(auth, email, password)
          .then((userData) => {
            setUser(userData.user);
            setIsLoading(false);
            console.log("userData", userData.user);
          })
          .catch((er) => {
            setIsLoading(false);
            setError(er.toString());
            console.log(er.message.toString());
          });
      };
    Login or Signup to reply.
  6. So, for me, that error came about when I had all my firebase configurations on separate page/file (Firebase.js) including the following:

    // Initialize Firebase
    export const app = initializeApp(firebaseConfig);
    
    export const db = getFirestore(app);
    
    export const auth = getAuth(app);
    
    export const storage = getStorage(app);
    

    So, the initial setup for Firebase was okay.

    However, I also had a separate page/file (App.js) where I called createUserWithEmailAndPassword(auth, email, password) as well as other built-in Firebase auth methods…

    But, I forgot to import app from Firebase.js and that error popped up after I called createUserWithEmailAndPassword.

    Once I did imported app, the error went away.

    Login or Signup to reply.
  7. the problem is with the app object which is not getting initialized before the context provider render’s

    You should import the ‘app’ from firebaseConfig.js or whatever.js file your firebase configuration is in, into your Context file.

    Note: make sure you are exporting the app from the configuration file

    import { app } from 'location/to/firebaseConfig.js';
    

    and in useEffect check for the ‘app’ if it exists then run the firebase-specific functions afterward and also add the ‘app’ to the dependency array.

       useEffect(() => {
        if (app) {
            //enter firebase-specific code here
    
            // for example:
            onAuthStateChanged(auth, (user) => {
            });
        }
    }, [app]);
    
    Login or Signup to reply.
  8. Just provide app inside the getAuth() function

    CreateUser File

    import { getAuth, createUserWithEmailAndPassword } from "firebase/auth"; 
    import {app} from './FirebaseConfig';
    
    
    export const auth = getAuth(app);
    
    export const createFirebaseUser = (email,password) =>{
    
      createUserWithEmailAndPassword(auth, email, password)
      .then((userCredential) => {
        
        const user = userCredential.user;
        
      })
      .catch((error) => {
        const errorCode = error.code;
        const errorMessage = error.message;
        
      });
    
    }  
    

    FireBaseConfig file

    import { initializeApp } from "firebase/app";
    import { getAnalytics } from "firebase/analytics";
    
    
    
    const firebaseConfig = {
      apiKey: "AIzaSyBqUdRQh_bAmZBESqrKl7qD0Ux7XVt4lkA",
      authDomain: "blink-app-d514b.firebaseapp.com",
      projectId: "blink-app-d514b",
      storageBucket: "blink-app-d514b.appspot.com",
      messagingSenderId: "237006400468",
      appId: "1:237006400468:web:b53ff39ee4cf1943d6c441",
      measurementId: "G-Z46RLK173Q"
    };
    
    // Initialize Firebase
    export const app = initializeApp(firebaseConfig);
    const analytics = getAnalytics(app);
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search