skip to Main Content

I have no idea why firebase auth is not persisting. My project is super simple so far, i have this sign in function.

await signInWithEmailAndPassword(auth, email, password);

And in the layout.tsx I have the onAuthStateChange

const unsubscribe = onAuthStateChanged(auth, (user) => {
      console.log("the current user is: ", user);
      if (!user) {
        router.replace("/sign-in");
        return;
      } else {
        router.replace("/main");
      }
    });

    return () => unsubscribe();
  }, []);

And that’s it. I can sign in and i get redirected, but when i reload the page there’s no user anymore.

Next version is 14.1.

Thanks in advance.

2

Answers


  1. The onAuthStateChanged triggers only when you sign/signout with firebase.
    So you might need to add your subscription inside context provider & store the user object in state & pass them as a prop to context provider.

         const authenticate = getAuth(initializeApp(firebaseConfig));
    
            const AuthContext = createContext<any>({});
            export const useAuth = () => useContext<any>(AuthContext); 
            export const AuthContextProvider = ({ children }: { children: React.ReactNode }) => {
              const [user, setUser] = useState<any>({ email: null, uid: null ,displayName : null});
              const [initializing, setInitializing] = useState<boolean>(true);
            
            
              useEffect(() => {
                const unsubscribe = onAuthStateChanged(authenticate, (user) => {
                  if (user) {
                    setUser({
                      email: user.email,
                      uid: user.uid,
                      displayName: user.displayName,
                      initializing:initializing,
                    });
                  } else {
                      
                    setUser({ email: null, uid: null, displayName:null, initializing:true});
                  }
                  setInitializing(false);
                });
                return () => unsubscribe();
              }, [initializing]);
            
            
              return (
                <AuthContext.Provider value={{ user }}>{initializing ? null : children}</AuthContext.Provider>
              );
            };
    

    then using the context, you can check from your page/layout/middleware to redirect

     const { user } = useAuth();   
     if(!user)
       router.replace("/sign-in");
        else
       router.replace("/main");
    
    Login or Signup to reply.
  2. Are you calling the signInWithEmailAndPassword inside of a server actions? It seems that when you are calling that function inside a server action or a server components it doesn’t save the response on the local storage of the browser making the onAuthStateChanged malfunction as its not getting any data from the local storage of the browser

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search