I'm facing an issue with the authentication flow in my React project with TypeScript and Vite, where I'm using Firebase. The problem arises when attempting to set the persistence type using setPersistence()
.
Contrary to what's stated in the official Firebase documentation, my web app logs the user out after a page reload. I've tried to resolve this using setPersistence().
Following the docs, here's what I tried initially:
const emailSignIn = async () => {
setPersistence(auth, browserLocalPersistence)
.then(() => {
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
console.log("Signed in: ", userCredential.user)
navigate('/profile');
})
.catch((error) => {
console.log("Failed to sign in: ", error);
});
})
.catch((error) => {
console.log("Failed to set persistence: ", error);
});
}
However, this didn't solve the issue. So, I attempted a different approach using a top-level declaration:
// imports
const auth = getAuth();
await setPersistence(auth, browserLocalPersistence);
function SignIn() {
// other function logic
const emailSignIn = async () => {
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
console.log("Signed in: ", userCredential.user)
navigate('/profile');
})
.catch((error) => {
console.log("Failed to sign in: ", error);
});
}
// return statement
}
export default SignIn
This approach worked when running on localhost using npm run dev
. However, when I attempted to build and deploy the application with npm run build
, I encountered the following error: Top-level await is not available in the configured target environment ("chrome87", "edge88", "es2020", "firefox78", "safari14" + 3 overrides)
.
I would greatly appreciate any insights or solutions to this issue.
The issue I was facing with Firebase's setPersistence() method wasn't directly related to the method itself, but rather because I had not implemented an auth state observer (rookie mistake!).
As pointed out by Doug in a comment, it's important to understand that the user isn't immediately registered as signed in upon page load. Instead, Firebase requires an auth state observer to accurately determine the user's authentication status.
Many thanks to Doug for solving my issue.