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
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.
then using the context, you can check from your page/layout/middleware to redirect
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