Authenticate with Firebase with a Phone Number Using JavaScript
Stay organized with collectionsSave and categorize content based on your preferences.
You can useFirebase Authenticationto sign in a user by sending an SMS message
to the user's phone. The user signs in using a one-time code contained in the
SMS message.
The easiest way to add phone number sign-in to your app is to useFirebaseUI,
which includes a drop-in sign-in widget that implements sign-in flows for phone
number sign-in, as well as password-based and federated sign-in. This document
describes how to implement a phone number sign-in flow using the Firebase SDK.
Authentication using only a phone number, while convenient, is less secure
than the other available methods, because possession of a phone number
can be easily transferred between users. Also, on devices with multiple user
profiles, any user that can receive SMS messages can sign in to an account using
the device's phone number.
If you use phone number based sign-in in your app, you should offer it
alongside more secure sign-in methods, and inform users of the security
tradeoffs of using phone number sign-in.
Enable Phone Number sign-in for your Firebase project
To sign in users by SMS, you must first enable the Phone Number sign-in
method for your Firebase project:
On theSign-in Methodpage, enable thePhone Numbersign-in method.
Optional: On theSettingspage, set a policy on the regions to which you want
to allow or deny SMS messages to be sent. Setting an SMS region policy can help protect your
apps from SMS abuse.
On the same page, if the domain that will host your app isn't listed in theOAuth redirect domainssection, add your domain. Note that localhost is not allowed as a hosted
domain for the purposes of phone auth.
Set up the reCAPTCHA verifier
Before you can sign in users with their phone numbers, you must set up
Firebase's reCAPTCHA verifier. Firebase uses reCAPTCHA to prevent abuse, such as
by ensuring that the phone number verification request comes from one of your
app's allowed domains.
You don't need to manually set up a reCAPTCHA client; when you use the
Firebase SDK'sRecaptchaVerifierobject, Firebase automatically
creates and handles any necessary client keys and secrets.
TheRecaptchaVerifierobject supportsinvisible
reCAPTCHA, which can often verify the user without requiring any user
action, as well as the reCAPTCHA widget, which always requires user interaction
to complete successfully.
The underlying rendered reCAPTCHA can be localized to the user's preference by updating the
language code on the Auth instance before rendering the reCAPTCHA. The aforementioned localization
will also apply to the SMS message sent to the user, containing the verification code.
Web
import{getAuth}from"firebase/auth";constauth=getAuth();auth.languageCode='it';// To apply the default browser preference instead of explicitly setting it.// auth.useDeviceLanguage();
To use an invisible reCAPTCHA, create aRecaptchaVerifierobject
with thesizeparameter set toinvisible, specifying
the ID of the button that submits your sign-in form. For example:
To use the visible reCAPTCHA widget, create an element on your page to
contain the widget, and then create aRecaptchaVerifierobject,
specifying the ID of the container when you do so. For example:
You can optionally set callback functions on theRecaptchaVerifierobject that are called when the user solves the
reCAPTCHA or the reCAPTCHA expires before the user submits the form:
Web
import{getAuth,RecaptchaVerifier}from"firebase/auth";constauth=getAuth();window.recaptchaVerifier=newRecaptchaVerifier(auth,'recaptcha-container',{'size':'normal','callback':(response)=>{// reCAPTCHA solved, allow signInWithPhoneNumber.// ...},'expired-callback':()=>{// Response expired. Ask user to solve reCAPTCHA again.// ...}});
To initiate phone number sign-in, present the user an interface that prompts
them to provide their phone number, and then callsignInWithPhoneNumberto request that Firebase send an
authentication code to the user's phone by SMS:
Get the user's phone number.
Legal requirements vary, but as a best practice
and to set expectations for your users, you should inform them that if they use
phone sign-in, they might receive an SMS message for verification and standard
rates apply.
CallsignInWithPhoneNumber, passing to it the user's phone
number and theRecaptchaVerifieryou created earlier.
Web
import{getAuth,signInWithPhoneNumber}from"firebase/auth";constphoneNumber=getPhoneNumberFromUserInput();constappVerifier=window.recaptchaVerifier;constauth=getAuth();signInWithPhoneNumber(auth,phoneNumber,appVerifier).then((confirmationResult)=>{// SMS sent. Prompt user to type the code from the message, then sign the// user in with confirmationResult.confirm(code).window.confirmationResult=confirmationResult;// ...}).catch((error)=>{// Error; SMS not sent// ...});
constphoneNumber=getPhoneNumberFromUserInput();constappVerifier=window.recaptchaVerifier;firebase.auth().signInWithPhoneNumber(phoneNumber,appVerifier).then((confirmationResult)=>{// SMS sent. Prompt user to type the code from the message, then sign the// user in with confirmationResult.confirm(code).window.confirmationResult=confirmationResult;// ...}).catch((error)=>{// Error; SMS not sent// ...});
ThesignInWithPhoneNumbermethod issues the reCAPTCHA challenge
to the user, and if the user passes the challenge, requests thatFirebase Authenticationsend an SMS message containing a verification code to the
user's phone.
Sign in the user with the verification code
After the call tosignInWithPhoneNumbersucceeds, prompt the
user to type the verification code they received by SMS. Then, sign in the user
by passing the code to theconfirmmethod of theConfirmationResultobject that was passed tosignInWithPhoneNumber's fulfillment handler (that is, itsthenblock). For example:
Web
constcode=getCodeFromUserInput();confirmationResult.confirm(code).then((result)=>{// User signed in successfully.constuser=result.user;// ...}).catch((error)=>{// User couldn't sign in (bad verification code?)// ...});
constcode=getCodeFromUserInput();confirmationResult.confirm(code).then((result)=>{// User signed in successfully.constuser=result.user;// ...}).catch((error)=>{// User couldn't sign in (bad verification code?)// ...});
If the call toconfirmsucceeded, the user is successfully
signed in.
Get the intermediate AuthCredential object
If you need to get anAuthCredentialobject for the user's
account, pass the verification code from the confirmation result and the
verification code toPhoneAuthProvider.credentialinstead of
callingconfirm:
Then, you can sign in the user with the credential:
firebase.auth().signInWithCredential(credential);
Test with fictional phone numbers
You can set up fictional phone numbers for development via theFirebaseconsole. Testing with fictional phone
numbers provides these benefits:
Test phone number authentication without consuming your usage quota.
Test phone number authentication without sending an actual SMS message.
Run consecutive tests with the same phone number without getting throttled. This
minimizes the risk of rejection during App store review process if the reviewer happens to use
the same phone number for testing.
Test readily in development environments without any additional effort, such as
the ability to develop in an iOS simulator or an Android emulator without Google Play Services.
Write integration tests without being blocked by security checks normally applied
on real phone numbers in a production environment.
Fictional phone numbers must meet these requirements:
Make sure you use phone numbers that are indeed fictional, and do not already exist.Firebase Authenticationdoes not allow you to set existing phone numbers used by real users as test numbers.
One option is to use 555 prefixed numbers as US test phone numbers, for example:+1 650-555-3434
Phone numbers have to be correctly formatted for length and other
constraints. They will still go through the same validation as a real user's phone number.
You can add up to 10 phone numbers for development.
Use test phone numbers/codes that are hard to guess and change
those frequently.
Create fictional phone numbers and verification codes
In theSign in methodtab, enable the Phone provider if you haven't already.
Open thePhone numbers for testingaccordion menu.
Provide the phone number you want to test, for example:+1 650-555-3434.
Provide the 6-digit verification code for that specific number, for example:654321.
Addthe number. If there's a need, you can delete the phone number and
its code by hovering over the corresponding row and clicking the trash icon.
Manual testing
You can directly start using a fictional phone number in your application. This allows you to
perform manual testing during development stages without running into quota issues or throttling.
You can also test directly from an iOS simulator or Android emulator without Google Play Services
installed.
When you provide the fictional phone number and send the verification code, no actual SMS is
sent. Instead, you need to provide the previously configured verification code to complete the sign
in.
On sign-in completion, a Firebase user is created with that phone number. The
user has the same behavior and properties as a real phone number user, and can accessRealtime Database/Cloud Firestoreand other services the same way. The ID token minted during
this process has the same signature as a real phone number user.
Another option is toset a test role via custom
claimson these users to differentiate them as fake users if you want to further restrict
access.
Integration testing
In addition to manual testing,Firebase Authenticationprovides APIs to help write integration tests
for phone auth testing. These APIs disable app verification by disabling the reCAPTCHA
requirement in web and silent push notifications in iOS. This makes automation testing possible in
these flows and easier to implement. In addition, they help provide the ability to test instant
verification flows on Android.
On web, setappVerificationDisabledForTestingtotruebefore rendering thefirebase.auth.RecaptchaVerifier. This resolves
the reCAPTCHA automatically, allowing you to pass the phone number without manually solving it. Note
that even though reCAPTCHA is disabled, using a non-fictional phone number will still fail to
complete sign in. Only fictional phone numbers can be used with this API.
Visible and invisible mock reCAPTCHA app verifiers behave differently when app verification is
disabled:
Visible reCAPTCHA: When the visible reCAPTCHA is rendered viaappVerifier.render(), it automatically resolves itself after a fraction of a second
delay. This is equivalent to a user clicking the reCAPTCHA immediately upon rendering. The reCAPTCHA
response will expire after some time and then auto-resolve again.
Invisible reCAPTCHA:
The invisible reCAPTCHA does not auto-resolve on rendering and instead does so on theappVerifier.verify()call or when the button anchor of the reCAPTCHA is
clicked after a fraction of a second delay. Similarly, the response will expire after some time and
will only auto-resolve either after theappVerifier.verify()call or when the
button anchor of the reCAPTCHA is clicked again.
Whenever a mock reCAPTCHA is resolved, the corresponding callback function is triggered as expected
with the fake response. If an expiration callback is also specified, it will trigger on expiration.
Next steps
After a user signs in for the first time, a new user account is created and
linked to the credentials—that is, the user name and password, phone
number, or auth provider information—the user signed in with. This new
account is stored as part of your Firebase project, and can be used to identify
a user across every app in your project, regardless of how the user signs in.
In your apps, the recommended way to know the auth status of your user is to
set an observer on theAuthobject. You can then get the user's
basic profile information from theUserobject. SeeManage Users.
In yourFirebase Realtime DatabaseandCloud StorageSecurity Rules, you can
get the signed-in user's unique user ID from theauthvariable,
and use it to control what data a user can access.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-09-04 UTC."],[],[],null,[]]