I have encountered a perplexing issue while setting up user registration with Firebase Authentication in my Next.js application. The problem arises when I try to register a new user with an unverified email address. Instead of following the correct flow to send an email verification, the code mistakenly jumps to the catch block and triggers an "auth/email-already-in-use" error.
Background:
I am developing a web application using Next.js. I have integrated Firebase Authentication into my Next.js application for managing user registration. The registration process includes creating a new user with an email and password. After successful registration, an email verification should be sent to the user. Current Problem:
When attempting to register a new user with an unverified email address, the code incorrectly goes to the catch block and triggers an "auth/email-already-in-use" error. This behavior is unexpected because the email is not already in use; it just needs verification. Expected Outcome:
Upon registering a new user with an unverified email address, the code should send an email verification without triggering the "auth/email-already-in-use" error. Actions Taken:
I have verified that the Firebase project settings allow unverified users. I have also checked the Firebase Authentication documentation and confirmed that the code aligns with best practices for handling email verification.
const handleRegistration = async (registerData: FormData) => {
setIsLoading(true);
try {
const app = initializeApp(fireconfig);
const auth = getAuth(app);
if (registerData.password.length < 8) {
setPasswordErrorMessage("Password must have at least 8 characters.");
return;
}
if (passwordErrorMessage !== "") {
setPasswordErrorMessage("");
}
const userCredential: any = await createUserWithEmailAndPassword(
auth,
registerData.email,
registerData.password
);
if (!userCredential.user.emailVerified) {
// Send email verification
await sendEmailVerification(userCredential.user);
toast({
title: "Email Verification Sent. Please verify your email.",
status: "success",
position: "top",
duration: null,
isClosable: true,
});
const userDocRef = doc(db, "users", userCredential.user.uid);
// Check if the user already exists in the 'users' collection
const userDocSnapshot = await getDoc(userDocRef);
if (!userDocSnapshot.exists()) {
const userData = {
firstName: registerData.firstName,
lastName: registerData.lastName,
email: registerData.email,
};
await setDoc(userDocRef, userData);
router.push("/login");
return;
}
}
} catch (error: any) {
if (error.code === "auth/email-already-in-use") {
setErrorMessage("That username is taken. Try another");
}
} finally {
setIsLoading(false);
}
};