How to Set Up Phone Authentication in Firebase
To set up
phone authentication in Firebase, enable Phone Sign-In in the Firebase Console under Authentication settings, then use the signInWithPhoneNumber method in your app to send a verification code to the user's phone. After the user enters the code, verify it with confirmationResult.confirm(code) to complete sign-in.Syntax
Phone authentication in Firebase uses these main parts:
- firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier): Sends a verification SMS to the phone number.
- confirmationResult.confirm(verificationCode): Verifies the code entered by the user to sign them in.
- RecaptchaVerifier: A security check to prevent abuse, usually shown as a widget.
javascript
const appVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container'); const phoneNumber = '+1234567890'; firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier) .then((confirmationResult) => { // SMS sent. Ask user for the code const verificationCode = window.prompt('Enter the verification code'); return confirmationResult.confirm(verificationCode); }) .then((result) => { // User signed in const user = result.user; }) .catch((error) => { // Handle errors });
Example
This example shows how to set up Firebase phone authentication in a web app. It initializes the reCAPTCHA, sends a verification SMS, and signs in the user after they enter the code.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Firebase Phone Auth Example</title> <script src="https://www.gstatic.com/firebasejs/9.22.1/firebase-app-compat.js"></script> <script src="https://www.gstatic.com/firebasejs/9.22.1/firebase-auth-compat.js"></script> </head> <body> <h2>Phone Authentication</h2> <div id="recaptcha-container"></div> <input type="text" id="phone-number" placeholder="Enter phone number (+1234567890)" /> <button id="send-code">Send Code</button> <br /><br /> <input type="text" id="verification-code" placeholder="Enter verification code" /> <button id="verify-code">Verify Code</button> <p id="message"></p> <script> // Your Firebase config const firebaseConfig = { apiKey: "YOUR_API_KEY", authDomain: "YOUR_AUTH_DOMAIN", projectId: "YOUR_PROJECT_ID", storageBucket: "YOUR_STORAGE_BUCKET", messagingSenderId: "YOUR_MESSAGING_SENDER_ID", appId: "YOUR_APP_ID" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); const auth = firebase.auth(); // Setup reCAPTCHA window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container', { size: 'normal', callback: (response) => { document.getElementById('send-code').disabled = false; }, 'expired-callback': () => { document.getElementById('send-code').disabled = true; } }); recaptchaVerifier.render(); let confirmationResult = null; document.getElementById('send-code').addEventListener('click', () => { const phoneNumber = document.getElementById('phone-number').value; auth.signInWithPhoneNumber(phoneNumber, window.recaptchaVerifier) .then((result) => { confirmationResult = result; document.getElementById('message').textContent = 'Code sent. Check your phone.'; }) .catch((error) => { document.getElementById('message').textContent = 'Error sending code: ' + error.message; }); }); document.getElementById('verify-code').addEventListener('click', () => { const code = document.getElementById('verification-code').value; if (!confirmationResult) { document.getElementById('message').textContent = 'Please request a code first.'; return; } confirmationResult.confirm(code) .then((result) => { const user = result.user; document.getElementById('message').textContent = 'Phone authentication successful! User ID: ' + user.uid; }) .catch((error) => { document.getElementById('message').textContent = 'Error verifying code: ' + error.message; }); }); </script> </body> </html>
Output
A web page with input fields for phone number and verification code, a visible reCAPTCHA widget, and messages showing success or error status.
Common Pitfalls
Common mistakes when setting up Firebase phone auth include:
- Not enabling Phone Sign-In in the Firebase Console under Authentication > Sign-in method.
- Forgetting to render the reCAPTCHA verifier before calling
signInWithPhoneNumber. - Using an invalid phone number format (must include country code, e.g., +1234567890).
- Not handling errors from SMS sending or code verification properly.
- Testing on localhost without configuring reCAPTCHA or using Firebase's test phone numbers.
javascript
/* Wrong: Calling signInWithPhoneNumber without reCAPTCHA */ firebase.auth().signInWithPhoneNumber('+1234567890', null) // This will fail .catch(error => console.error('Error:', error.message)); /* Right: Initialize and render reCAPTCHA first */ const appVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container'); firebase.auth().signInWithPhoneNumber('+1234567890', appVerifier) .then(confirmationResult => { /* proceed */ });
Quick Reference
Tips for smooth Firebase phone authentication setup:
- Enable Phone Sign-In in Firebase Console.
- Use
RecaptchaVerifierto prevent abuse. - Always include country code in phone numbers.
- Use Firebase test phone numbers during development to avoid SMS costs.
- Handle errors gracefully to improve user experience.
Key Takeaways
Enable Phone Sign-In in Firebase Console before using phone auth.
Use RecaptchaVerifier to secure the phone sign-in process.
Send verification SMS with signInWithPhoneNumber and confirm code with confirmationResult.confirm().
Always include the country code in phone numbers for correct formatting.
Use Firebase test phone numbers during development to avoid real SMS charges.