I’m trying to implement OTP authentication using Firebase in my React 18 application. When a user enters their mobile number, they should receive an OTP. After entering the OTP, they should be asked to provide additional information like email, password, and username.
The problem is with reCAPTCHA verification. Here is the relevant part of my code:
declare global {
interface Window {
recaptchaVerifier: RecaptchaVerifier;
}
}
Initializing reCAPTCHA:
const initializeRecaptcha = () => {
if (!window.recaptchaVerifier) {
window.recaptchaVerifier = new RecaptchaVerifier(auth, 'recaptcha-container', {
size: 'normal',
callback: (response: any) => {
handleSendOtp();
},
'expired-callback': () => {
console.error('reCAPTCHA expired. Please try again.');
}
});
window.recaptchaVerifier.render().catch((error) => {
console.error('Error initializing reCAPTCHA', error);
});
}
};
Using useEffect to Initialize reCAPTCHA:
useEffect(() => {
if (open) {
initializeRecaptcha();
}
}, [open]);
Sending OTP:
const handleSendOtp = async () => {
if (isSending) return;
setIsSending(true);
try {
const appVerifier = await window.recaptchaVerifier;
const formattedPhoneNumber = formatPhoneNumber(phoneNumber);
if (!formattedPhoneNumber) {
console.error('Invalid phone number format');
setIsSending(false);
return;
}
const result = await signInWithPhoneNumber(auth, formattedPhoneNumber, appVerifier);
setConfirmationResult(result);
} catch (error: any) {
console.error('Error during OTP send', error);
if (error.code === 'auth/too-many-requests') {
console.error('Too many attempts. Please try again later.');
}
} finally {
setIsSending(false);
}
};
Verifying OTP:
const handleVerifyOtp = async () => {
if (!confirmationResult) return;
try {
const result = await confirmationResult.confirm(otp);
onVerified(result.user.phoneNumber!);
} catch (error) {
console.error('Error during OTP verification', error);
}
};
Despite trying to remove the reCAPTCHA initialization from useEffect, I am still getting the following error in the browser:
Unexpected Application Error!
Firebase: Error (auth/argument-error).
FirebaseError: Firebase: Error (auth/argument-error).
at createErrorInternal (http://localhost:3000/node_modules/.vite/deps/firebase_auth.js?