Skip to content

Latest commit

 

History

History
2167 lines (1467 loc) · 98.6 KB

auth.md

File metadata and controls

2167 lines (1467 loc) · 98.6 KB

Project: /docs/reference/js/_project.yaml Book: /docs/reference/_book.yaml page_type: reference

{% comment %} DO NOT EDIT THIS FILE! This is generated by the JS SDK team, and any local changes will be overwritten. Changes should be made in the source code at https://github.com/firebase/firebase-js-sdk {% endcomment %}

auth package

Firebase Authentication

Functions

FunctionDescription
function(app, ...)
getAuth(app)Returns the Auth instance associated with the provided FirebaseApp. If no instance exists, initializes an Auth instance with platform-specific default dependencies.
initializeAuth(app, deps)Initializes an Auth instance with fine-grained control over Dependencies.
function(storage, ...)
getReactNativePersistence(storage)Returns a persistence object that wraps AsyncStorage imported from react-native or @react-native-community/async-storage, and can be used in the persistence dependency field in initializeAuth().
function(auth, ...)
applyActionCode(auth, oobCode)Applies a verification code sent to the user by email or other out-of-band mechanism.
beforeAuthStateChanged(auth, callback, onAbort)Adds a blocking callback that runs before an auth state change sets a new user.
checkActionCode(auth, oobCode)Checks a verification code sent to the user by email or other out-of-band mechanism.
confirmPasswordReset(auth, oobCode, newPassword)Completes the password reset process, given a confirmation code and new password.
connectAuthEmulator(auth, url, options)Changes the Auth instance to communicate with the Firebase Auth Emulator, instead of production Firebase Auth services.
createUserWithEmailAndPassword(auth, email, password)Creates a new user account associated with the specified email address and password.
fetchSignInMethodsForEmail(auth, email)Gets the list of possible sign in methods for the given email address. This method returns an empty list when Email Enumeration Protection is enabled, irrespective of the number of authentication methods available for the given email.
getMultiFactorResolver(auth, error)Provides a MultiFactorResolver suitable for completion of a multi-factor flow.
getRedirectResult(auth, resolver)Returns a UserCredential from the redirect-based sign-in flow.
initializeRecaptchaConfig(auth)Loads the reCAPTCHA configuration into the Auth instance.
isSignInWithEmailLink(auth, emailLink)Checks if an incoming link is a sign-in with email link suitable for signInWithEmailLink().
onAuthStateChanged(auth, nextOrObserver, error, completed)Adds an observer for changes to the user's sign-in state.
onIdTokenChanged(auth, nextOrObserver, error, completed)Adds an observer for changes to the signed-in user's ID token.
revokeAccessToken(auth, token)Revokes the given access token. Currently only supports Apple OAuth access tokens.
sendPasswordResetEmail(auth, email, actionCodeSettings)Sends a password reset email to the given email address. This method does not throw an error when there's no user account with the given email address and Email Enumeration Protection is enabled.
sendSignInLinkToEmail(auth, email, actionCodeSettings)Sends a sign-in email link to the user with the specified email.
setPersistence(auth, persistence)Changes the type of persistence on the Auth instance for the currently saved Auth session and applies this type of persistence for future sign-in requests, including sign-in with redirect requests.
signInAnonymously(auth)Asynchronously signs in as an anonymous user.
signInWithCredential(auth, credential)Asynchronously signs in with the given credentials.
signInWithCustomToken(auth, customToken)Asynchronously signs in using a custom token.
signInWithEmailAndPassword(auth, email, password)Asynchronously signs in using an email and password.
signInWithEmailLink(auth, email, emailLink)Asynchronously signs in using an email and sign-in email link.
signInWithPhoneNumber(auth, phoneNumber, appVerifier)Asynchronously signs in using a phone number.
signInWithPopup(auth, provider, resolver)Authenticates a Firebase client using a popup-based OAuth authentication flow.
signInWithRedirect(auth, provider, resolver)Authenticates a Firebase client using a full-page redirect flow.
signOut(auth)Signs out the current user.
updateCurrentUser(auth, user)Asynchronously sets the provided user as Auth.currentUser on the Auth instance.
useDeviceLanguage(auth)Sets the current language to the default device/browser preference.
validatePassword(auth, password)Validates the password against the password policy configured for the project or tenant.
verifyPasswordResetCode(auth, code)Checks a password reset code sent to the user by email or other out-of-band mechanism.
function(link, ...)
parseActionCodeURL(link)Parses the email action link string and returns an ActionCodeURL if the link is valid, otherwise returns null.
function(user, ...)
deleteUser(user)Deletes and signs out the user.
getIdToken(user, forceRefresh)Returns a JSON Web Token (JWT) used to identify the user to a Firebase service.
getIdTokenResult(user, forceRefresh)Returns a deserialized JSON Web Token (JWT) used to identify the user to a Firebase service.
linkWithCredential(user, credential)Links the user account with the given credentials.
linkWithPhoneNumber(user, phoneNumber, appVerifier)Links the user account with the given phone number.
linkWithPopup(user, provider, resolver)Links the authenticated provider to the user account using a pop-up based OAuth flow.
linkWithRedirect(user, provider, resolver)Links the OAuthProvider to the user account using a full-page redirect flow.
multiFactor(user)The MultiFactorUser corresponding to the user.
reauthenticateWithCredential(user, credential)Re-authenticates a user using a fresh credential.
reauthenticateWithPhoneNumber(user, phoneNumber, appVerifier)Re-authenticates a user using a fresh phone credential.
reauthenticateWithPopup(user, provider, resolver)Reauthenticates the current user with the specified OAuthProvider using a pop-up based OAuth flow.
reauthenticateWithRedirect(user, provider, resolver)Reauthenticates the current user with the specified OAuthProvider using a full-page redirect flow.
reload(user)Reloads user account data, if signed in.
sendEmailVerification(user, actionCodeSettings)Sends a verification email to a user.
unlink(user, providerId)Unlinks a provider from a user account.
updateEmail(user, newEmail)Updates the user's email address.
updatePassword(user, newPassword)Updates the user's password.
updatePhoneNumber(user, credential)Updates the user's phone number.
updateProfile(user, { displayName, photoURL: photoUrl })Updates a user's profile data.
verifyBeforeUpdateEmail(user, newEmail, actionCodeSettings)Sends a verification email to a new email address.
function(userCredential, ...)
getAdditionalUserInfo(userCredential)Extracts provider specific AdditionalUserInfo for the given credential.

Classes

ClassDescription
ActionCodeURLA utility class to parse email action URLs such as password reset, email verification, email link sign in, etc.
AuthCredentialInterface that represents the credentials returned by an AuthProvider.
EmailAuthCredentialInterface that represents the credentials returned by EmailAuthProvider for ProviderId.PASSWORD
EmailAuthProviderProvider for generating EmailAuthCredential.
FacebookAuthProviderProvider for generating an OAuthCredential for ProviderId.FACEBOOK.
GithubAuthProviderProvider for generating an OAuthCredential for ProviderId.GITHUB.
GoogleAuthProviderProvider for generating an OAuthCredential for ProviderId.GOOGLE.
OAuthCredentialRepresents the OAuth credentials returned by an OAuthProvider.
OAuthProviderProvider for generating generic OAuthCredential.
PhoneAuthCredentialRepresents the credentials returned by PhoneAuthProvider.
PhoneAuthProviderProvider for generating an PhoneAuthCredential.
PhoneMultiFactorGeneratorProvider for generating a PhoneMultiFactorAssertion.
RecaptchaVerifierAn reCAPTCHA-based application verifier.
SAMLAuthProviderAn AuthProvider for SAML.
TotpMultiFactorGeneratorProvider for generating a TotpMultiFactorAssertion.
TotpSecretProvider for generating a TotpMultiFactorAssertion.Stores the shared secret key and other parameters to generate time-based OTPs. Implements methods to retrieve the shared secret key and generate a QR code URL.
TwitterAuthProviderProvider for generating an OAuthCredential for ProviderId.TWITTER.

Interfaces

InterfaceDescription
ActionCodeInfoA response from checkActionCode().
ActionCodeSettingsAn interface that defines the required continue/state URL with optional Android and iOS bundle identifiers.
AdditionalUserInfoA structure containing additional user information from a federated identity provider.
ApplicationVerifierA verifier for domain verification and abuse prevention.
AuthInterface representing Firebase Auth service.
AuthErrorInterface for an Auth error.
AuthErrorMapA mapping of error codes to error messages.
AuthProviderInterface that represents an auth provider, used to facilitate creating AuthCredential.
AuthSettingsInterface representing an Auth instance's settings.
ConfigInterface representing the Auth config.
ConfirmationResultA result from a phone number sign-in, link, or reauthenticate call.
DependenciesThe dependencies that can be used to initialize an Auth instance.
EmulatorConfigConfiguration of Firebase Authentication Emulator.
IdTokenResultInterface representing ID token result obtained from User.getIdTokenResult().
MultiFactorAssertionThe base class for asserting ownership of a second factor.
MultiFactorErrorThe error thrown when the user needs to provide a second factor to sign in successfully.
MultiFactorInfoA structure containing the information of a second factor entity.
MultiFactorResolverThe class used to facilitate recovery from MultiFactorError when a user needs to provide a second factor to sign in.
MultiFactorSessionAn interface defining the multi-factor session object used for enrolling a second factor on a user or helping sign in an enrolled user with a second factor.
MultiFactorUserAn interface that defines the multi-factor related properties and operations pertaining to a User.
OAuthCredentialOptionsDefines the options for initializing an OAuthCredential.
ParsedTokenInterface representing a parsed ID token.
PasswordPolicyA structure specifying password policy requirements.
PasswordValidationStatusA structure indicating which password policy requirements were met or violated and what the requirements are.
PersistenceAn interface covering the possible persistence mechanism types.
PhoneMultiFactorAssertionThe class for asserting ownership of a phone second factor. Provided by PhoneMultiFactorGenerator.assertion().
PhoneMultiFactorEnrollInfoOptionsOptions used for enrolling a second factor.
PhoneMultiFactorInfoThe subclass of the MultiFactorInfo interface for phone number second factors. The factorId of this second factor is FactorId.PHONE.
PhoneMultiFactorSignInInfoOptionsOptions used for signing in with a second factor.
PhoneSingleFactorInfoOptionsOptions used for single-factor sign-in.
PopupRedirectResolverA resolver used for handling DOM specific operations like signInWithPopup() or signInWithRedirect().
ReactNativeAsyncStorageInterface for a supplied AsyncStorage.
RecaptchaParametersInterface representing reCAPTCHA parameters.See the reCAPTCHA docs for the list of accepted parameters. All parameters are accepted except for sitekey: Firebase Auth provisions a reCAPTCHA for each project and will configure the site key upon rendering.For an invisible reCAPTCHA, set the size key to invisible.
TotpMultiFactorAssertionThe class for asserting ownership of a TOTP second factor. Provided by TotpMultiFactorGenerator.assertionForEnrollment() and TotpMultiFactorGenerator.assertionForSignIn().
TotpMultiFactorInfoThe subclass of the MultiFactorInfo interface for TOTP second factors. The factorId of this second factor is FactorId.TOTP.
UserA user account.
UserCredentialA structure containing a User, the OperationType, and the provider ID.
UserInfoUser profile information, visible only to the Firebase project's apps.
UserMetadataInterface representing a user's metadata.

Variables

VariableDescription
ActionCodeOperationAn enumeration of the possible email action types.
AuthErrorCodesA map of potential Auth error codes, for easier comparison with errors thrown by the SDK.
browserCookiePersistence(Public Preview) An implementation of Persistence of type COOKIE, for use on the client side in applications leveraging hybrid rendering and middleware.
browserLocalPersistenceAn implementation of Persistence of type LOCAL using localStorage for the underlying storage.
browserPopupRedirectResolverAn implementation of PopupRedirectResolver suitable for browser based applications.
browserSessionPersistenceAn implementation of Persistence of SESSION using sessionStorage for the underlying storage.
cordovaPopupRedirectResolverAn implementation of PopupRedirectResolver suitable for Cordova based applications.
debugErrorMapA verbose error map with detailed descriptions for most error codes.See discussion at AuthErrorMap
FactorIdAn enum of factors that may be used for multifactor authentication.
indexedDBLocalPersistenceAn implementation of Persistence of type LOCAL using indexedDB for the underlying storage.
inMemoryPersistenceAn implementation of Persistence of type 'NONE'.
OperationTypeEnumeration of supported operation types.
prodErrorMapA minimal error map with all verbose error messages stripped.See discussion at AuthErrorMap
ProviderIdEnumeration of supported providers.
SignInMethodEnumeration of supported sign-in methods.

Type Aliases

Type AliasDescription
CustomParametersMap of OAuth Custom Parameters.
NextOrObserverType definition for an event callback.
PhoneInfoOptionsThe information required to verify the ownership of a phone number.
UserProfileUser profile used in AdditionalUserInfo.

function(app, ...)

getAuth(app) {:#getauth_cf608e1}

Returns the Auth instance associated with the provided FirebaseApp. If no instance exists, initializes an Auth instance with platform-specific default dependencies.

Signature:

exportdeclarefunctiongetAuth(app?: FirebaseApp): Auth;

Parameters

ParameterTypeDescription
appFirebaseAppThe Firebase App.

Returns:

Auth

initializeAuth(app, deps) {:#initializeauth_ca77c9b}

Initializes an Auth instance with fine-grained control over Dependencies.

This function allows more control over the Auth instance than getAuth(). getAuth uses platform-specific defaults to supply the Dependencies. In general, getAuth is the easiest way to initialize Auth and works for most use cases. Use initializeAuth if you need control over which persistence layer is used, or to minimize bundle size if you're not using either signInWithPopup or signInWithRedirect.

For example, if your app only uses anonymous accounts and you only want accounts saved for the current session, initialize Auth with:

constauth=initializeAuth(app,{persistence: browserSessionPersistence,popupRedirectResolver: undefined,});

Signature:

exportdeclarefunctioninitializeAuth(app: FirebaseApp,deps?: Dependencies): Auth;

Parameters

ParameterTypeDescription
appFirebaseApp
depsDependencies

Returns:

Auth

function(storage, ...)

getReactNativePersistence(storage) {:#getreactnativepersistence_bab4ada}

Returns a persistence object that wraps AsyncStorage imported from react-native or @react-native-community/async-storage, and can be used in the persistence dependency field in initializeAuth().

Signature:

exportdeclarefunctiongetReactNativePersistence(storage: ReactNativeAsyncStorage): Persistence;

Parameters

ParameterTypeDescription
storageReactNativeAsyncStorage

Returns:

Persistence

function(auth, ...)

applyActionCode(auth, oobCode) {:#applyactioncode_d2ae15a}

Applies a verification code sent to the user by email or other out-of-band mechanism.

Signature:

exportdeclarefunctionapplyActionCode(auth: Auth,oobCode: string): Promise<void>;

Parameters

ParameterTypeDescription
authAuthThe Auth instance.
oobCodestringA verification code sent to the user.

Returns:

Promise<void>

beforeAuthStateChanged(auth, callback, onAbort) {:#beforeauthstatechanged_22f2ab6}

Adds a blocking callback that runs before an auth state change sets a new user.

Signature:

exportdeclarefunctionbeforeAuthStateChanged(auth: Auth,callback: (user: User|null)=>void|Promise<void>,onAbort?: ()=>void): Unsubscribe;

Parameters

ParameterTypeDescription
authAuthThe Auth instance.
callback(user: User | null) => void | Promise<void>callback triggered before new user value is set. If this throws, it blocks the user from being set.
onAbort() => voidcallback triggered if a later beforeAuthStateChanged() callback throws, allowing you to undo any side effects.

Returns:

Unsubscribe

checkActionCode(auth, oobCode) {:#checkactioncode_d2ae15a}

Checks a verification code sent to the user by email or other out-of-band mechanism.

Signature:

exportdeclarefunctioncheckActionCode(auth: Auth,oobCode: string): Promise<ActionCodeInfo>;

Parameters

ParameterTypeDescription
authAuthThe Auth instance.
oobCodestringA verification code sent to the user.

Returns:

Promise<ActionCodeInfo>

metadata about the code.

confirmPasswordReset(auth, oobCode, newPassword) {:#confirmpasswordreset_749dad8}

Completes the password reset process, given a confirmation code and new password.

Signature:

exportdeclarefunctionconfirmPasswordReset(auth: Auth,oobCode: string,newPassword: string): Promise<void>;

Parameters

ParameterTypeDescription
authAuthThe Auth instance.
oobCodestringA confirmation code sent to the user.
newPasswordstringThe new password.

Returns:

Promise<void>

connectAuthEmulator(auth, url, options) {:#connectauthemulator_657c7e5}

Changes the Auth instance to communicate with the Firebase Auth Emulator, instead of production Firebase Auth services.

This must be called synchronously immediately following the first call to initializeAuth(). Do not use with production credentials as emulator traffic is not encrypted.

Signature:

exportdeclarefunctionconnectAuthEmulator(auth: Auth,url: string,options?: {disableWarnings: boolean;}): void;

Parameters

ParameterTypeDescription
authAuthThe Auth instance.
urlstringThe URL at which the emulator is running (eg, 'http://localhost:9099').
options{ disableWarnings: boolean; }Optional. options.disableWarnings defaults to false. Set it to true to disable the warning banner attached to the DOM.

Returns:

void

Example

connectAuthEmulator(auth,'http://127.0.0.1:9099',{disableWarnings: true});

createUserWithEmailAndPassword(auth, email, password) {:#createuserwithemailandpassword_21ad33b}

Creates a new user account associated with the specified email address and password.

On successful creation of the user account, this user will also be signed in to your application.

User account creation can fail if the account already exists or the password is invalid.

This method is not supported on Auth instances created with a FirebaseServerApp.

Note: The email address acts as a unique identifier for the user and enables an email-based password reset. This function will create a new user account and set the initial user password.

Signature:

exportdeclarefunctioncreateUserWithEmailAndPassword(auth: Auth,email: string,password: string): Promise<UserCredential>;

Parameters

ParameterTypeDescription
authAuthThe Auth instance.
emailstringThe user's email address.
passwordstringThe user's chosen password.

Returns:

Promise<UserCredential>

fetchSignInMethodsForEmail(auth, email) {:#fetchsigninmethodsforemail_efb3887}

Gets the list of possible sign in methods for the given email address. This method returns an empty list when Email Enumeration Protection is enabled, irrespective of the number of authentication methods available for the given email.

This is useful to differentiate methods of sign-in for the same provider, eg. EmailAuthProvider which has 2 methods of sign-in, SignInMethod.EMAIL_PASSWORD and SignInMethod.EMAIL_LINK.

Signature:

exportdeclarefunctionfetchSignInMethodsForEmail(auth: Auth,email: string): Promise<string[]>;

Parameters

ParameterTypeDescription
authAuthThe Auth instance.
emailstringThe user's email address.Deprecated. Migrating off of this method is recommended as a security best-practice. Learn more in the Identity Platform documentation for Email Enumeration Protection.

Returns:

Promise<string[]>

getMultiFactorResolver(auth, error) {:#getmultifactorresolver_201ba61}

Provides a MultiFactorResolver suitable for completion of a multi-factor flow.

Signature:

exportdeclarefunctiongetMultiFactorResolver(auth: Auth,error: MultiFactorError): MultiFactorResolver;

Parameters

ParameterTypeDescription
authAuthThe Auth instance.
errorMultiFactorErrorThe MultiFactorError raised during a sign-in, or reauthentication operation.

Returns:

MultiFactorResolver

getRedirectResult(auth, resolver) {:#getredirectresult_c35dc1f}

Returns a UserCredential from the redirect-based sign-in flow.

If sign-in succeeded, returns the signed in user. If sign-in was unsuccessful, fails with an error. If no redirect operation was called, returns null.

This method does not work in a Node.js environment or with Auth instances created with a FirebaseServerApp.

Signature:

exportdeclarefunctiongetRedirectResult(auth: Auth,resolver?: PopupRedirectResolver): Promise<UserCredential|null>;

Parameters

ParameterTypeDescription
authAuthThe Auth instance.
resolverPopupRedirectResolverAn instance of PopupRedirectResolver, optional if already supplied to initializeAuth() or provided by getAuth().

Returns:

Promise<UserCredential | null>

Example

// Sign in using a redirect.constprovider=newFacebookAuthProvider();// You can add additional scopes to the provider:provider.addScope('user_birthday');// Start a sign in process for an unauthenticated user.awaitsignInWithRedirect(auth,provider);// This will trigger a full page redirect away from your app// After returning from the redirect when your app initializes you can obtain the resultconstresult=awaitgetRedirectResult(auth);if(result){// This is the signed-in userconstuser=result.user;// This gives you a Facebook Access Token.constcredential=provider.credentialFromResult(auth,result);consttoken=credential.accessToken;}// As this API can be used for sign-in, linking and reauthentication,// check the operationType to determine what triggered this redirect// operation.constoperationType=result.operationType;

initializeRecaptchaConfig(auth) {:#initializerecaptchaconfig_2a61ea7}

Loads the reCAPTCHA configuration into the Auth instance.

This will load the reCAPTCHA config, which indicates whether the reCAPTCHA verification flow should be triggered for each auth provider, into the current Auth session.

If initializeRecaptchaConfig() is not invoked, the auth flow will always start without reCAPTCHA verification. If the provider is configured to require reCAPTCHA verification, the SDK will transparently load the reCAPTCHA config and restart the auth flows.

Thus, by calling this optional method, you will reduce the latency of future auth flows. Loading the reCAPTCHA config early will also enhance the signal collected by reCAPTCHA.

This method does not work in a Node.js environment.

Signature:

exportdeclarefunctioninitializeRecaptchaConfig(auth: Auth): Promise<void>;

Parameters

ParameterTypeDescription
authAuthThe Auth instance.

Returns:

Promise<void>

Example

initializeRecaptchaConfig(auth);

isSignInWithEmailLink(auth, emailLink) {:#issigninwithemaillink_db04f1d}

Checks if an incoming link is a sign-in with email link suitable for signInWithEmailLink().

Signature:

exportdeclarefunctionisSignInWithEmailLink(auth: Auth,emailLink: string): boolean;

Parameters

ParameterTypeDescription
authAuthThe Auth instance.
emailLinkstringThe link sent to the user's email address.

Returns:

boolean

onAuthStateChanged(auth, nextOrObserver, error, completed) {:#onauthstatechanged_b0d07ab}

Adds an observer for changes to the user's sign-in state.

To keep the old behavior, see onIdTokenChanged().

Signature:

exportdeclarefunctiononAuthStateChanged(auth: Auth,nextOrObserver: NextOrObserver<User>,error?: ErrorFn,completed?: CompleteFn): Unsubscribe;

Parameters

ParameterTypeDescription
authAuthThe Auth instance.
nextOrObserverNextOrObserver<User>callback triggered on change.
errorErrorFnDeprecated. This callback is never triggered. Errors on signing in/out can be caught in promises returned from sign-in/sign-out functions.
completedCompleteFnDeprecated. This callback is never triggered.

Returns:

Unsubscribe

onIdTokenChanged(auth, nextOrObserver, error, completed) {:#onidtokenchanged_b0d07ab}

Adds an observer for changes to the signed-in user's ID token.

This includes sign-in, sign-out, and token refresh events. This will not be triggered automatically upon ID token expiration. Use User.getIdToken() to refresh the ID token.

Signature:

exportdeclarefunctiononIdTokenChanged(auth: Auth,nextOrObserver: NextOrObserver<User>,error?: ErrorFn,completed?: CompleteFn): Unsubscribe;

Parameters

ParameterTypeDescription
authAuthThe Auth instance.
nextOrObserverNextOrObserver<User>callback triggered on change.
errorErrorFnDeprecated. This callback is never triggered. Errors on signing in/out can be caught in promises returned from sign-in/sign-out functions.
completedCompleteFnDeprecated. This callback is never triggered.

Returns:

Unsubscribe

revokeAccessToken(auth, token) {:#revokeaccesstoken_5556ad5}

Revokes the given access token. Currently only supports Apple OAuth access tokens.

Signature:

exportdeclarefunctionrevokeAccessToken(auth: Auth,token: string): Promise<void>;

Parameters

ParameterTypeDescription
authAuthThe Auth instance.
tokenstringThe Apple OAuth access token.

Returns:

Promise<void>

sendPasswordResetEmail(auth, email, actionCodeSettings) {:#sendpasswordresetemail_95b079b}

Sends a password reset email to the given email address. This method does not throw an error when there's no user account with the given email address and Email Enumeration Protection is enabled.

To complete the password reset, call confirmPasswordReset() with the code supplied in the email sent to the user, along with the new password specified by the user.

Signature:

exportdeclarefunctionsendPasswordResetEmail(auth: Auth,email: string,actionCodeSettings?: ActionCodeSettings): Promise<void>;

Parameters

ParameterTypeDescription
authAuthThe Auth instance.
emailstringThe user's email address.
actionCodeSettingsActionCodeSettingsThe ActionCodeSettings.

Returns:

Promise<void>

Example

constactionCodeSettings={url: 'https://www.example.com/?email=user@example.com',iOS: {bundleId: 'com.example.ios'},android: {packageName: 'com.example.android',installApp: true,minimumVersion: '12'},handleCodeInApp: true};awaitsendPasswordResetEmail(auth,'user@example.com',actionCodeSettings);// Obtain code from user.awaitconfirmPasswordReset('user@example.com',code);

sendSignInLinkToEmail(auth, email, actionCodeSettings) {:#sendsigninlinktoemail_95b079b}

Sends a sign-in email link to the user with the specified email.

The sign-in operation has to always be completed in the app unlike other out of band email actions (password reset and email verifications). This is because, at the end of the flow, the user is expected to be signed in and their Auth state persisted within the app.

To complete sign in with the email link, call signInWithEmailLink() with the email address and the email link supplied in the email sent to the user.

Signature:

exportdeclarefunctionsendSignInLinkToEmail(auth: Auth,email: string,actionCodeSettings: ActionCodeSettings): Promise<void>;

Parameters

ParameterTypeDescription
authAuth
emailstringThe user's email address.
actionCodeSettingsActionCodeSettingsThe ActionCodeSettings.

Returns:

Promise<void>

Example

constactionCodeSettings={url: 'https://www.example.com/?email=user@example.com',iOS: {bundleId: 'com.example.ios'},android: {packageName: 'com.example.android',installApp: true,minimumVersion: '12'},handleCodeInApp: true};awaitsendSignInLinkToEmail(auth,'user@example.com',actionCodeSettings);// Obtain emailLink from the user.if(isSignInWithEmailLink(auth,emailLink)){awaitsignInWithEmailLink(auth,'user@example.com',emailLink);}

setPersistence(auth, persistence) {:#setpersistence_a3592ac}

Changes the type of persistence on the Auth instance for the currently saved Auth session and applies this type of persistence for future sign-in requests, including sign-in with redirect requests.

This makes it easy for a user signing in to specify whether their session should be remembered or not. It also makes it easier to never persist the Auth state for applications that are shared by other users or have sensitive data.

This method does not work in a Node.js environment or with Auth instances created with a FirebaseServerApp.

Signature:

exportdeclarefunctionsetPersistence(auth: Auth,persistence: Persistence): Promise<void>;

Parameters

ParameterTypeDescription
authAuthThe Auth instance.
persistencePersistenceThe Persistence to use.

Returns:

Promise<void>

A Promise that resolves once the persistence change has completed

Example

setPersistence(auth,browserSessionPersistence);

signInAnonymously(auth) {:#signinanonymously_2a61ea7}

Asynchronously signs in as an anonymous user.

If there is already an anonymous user signed in, that user will be returned; otherwise, a new anonymous user identity will be created and returned.

This method is not supported by Auth instances created with a FirebaseServerApp.

Signature:

exportdeclarefunctionsignInAnonymously(auth: Auth): Promise<UserCredential>;

Parameters

ParameterTypeDescription
authAuthThe Auth instance.

Returns:

Promise<UserCredential>

signInWithCredential(auth, credential) {:#signinwithcredential_8074518}

Asynchronously signs in with the given credentials.

An AuthProvider can be used to generate the credential.

This method is not supported by Auth instances created with a FirebaseServerApp.

Signature:

exportdeclarefunctionsignInWithCredential(auth: Auth,credential: AuthCredential): Promise<UserCredential>;

Parameters

ParameterTypeDescription
authAuthThe Auth instance.
credentialAuthCredentialThe auth credential.

Returns:

Promise<UserCredential>

signInWithCustomToken(auth, customToken) {:#signinwithcustomtoken_32af683}

Asynchronously signs in using a custom token.

Custom tokens are used to integrate Firebase Auth with existing auth systems, and must be generated by an auth backend using the createCustomToken method in the Admin SDK .

Fails with an error if the token is invalid, expired, or not accepted by the Firebase Auth service.

This method is not supported by Auth instances created with a FirebaseServerApp.

Signature:

exportdeclarefunctionsignInWithCustomToken(auth: Auth,customToken: string): Promise<UserCredential>;

Parameters

ParameterTypeDescription
authAuthThe Auth instance.
customTokenstringThe custom token to sign in with.

Returns:

Promise<UserCredential>

signInWithEmailAndPassword(auth, email, password) {:#signinwithemailandpassword_21ad33b}

Asynchronously signs in using an email and password.

Fails with an error if the email address and password do not match. When Email Enumeration Protection is enabled, this method fails with "auth/invalid-credential" in case of an invalid email/password.

This method is not supported on Auth instances created with a FirebaseServerApp.

Note: The user's password is NOT the password used to access the user's email account. The email address serves as a unique identifier for the user, and the password is used to access the user's account in your Firebase project. See also: createUserWithEmailAndPassword().

Signature:

exportdeclarefunctionsignInWithEmailAndPassword(auth: Auth,email: string,password: string): Promise<UserCredential>;

Parameters

ParameterTypeDescription
authAuthThe Auth instance.
emailstringThe users email address.
passwordstringThe users password.

Returns:

Promise<UserCredential>

signInWithEmailLink(auth, email, emailLink) {:#signinwithemaillink_ed14c53}

Asynchronously signs in using an email and sign-in email link.

If no link is passed, the link is inferred from the current URL.

Fails with an error if the email address is invalid or OTP in email link expires.

This method is not supported by Auth instances created with a FirebaseServerApp.

Note: Confirm the link is a sign-in email link before calling this method firebase.auth.Auth.isSignInWithEmailLink.

Signature:

exportdeclarefunctionsignInWithEmailLink(auth: Auth,email: string,emailLink?: string): Promise<UserCredential>;

Parameters

ParameterTypeDescription
authAuthThe Auth instance.
emailstringThe user's email address.
emailLinkstringThe link sent to the user's email address.

Returns:

Promise<UserCredential>

Example

constactionCodeSettings={url: 'https://www.example.com/?email=user@example.com',iOS: {bundleId: 'com.example.ios'},android: {packageName: 'com.example.android',installApp: true,minimumVersion: '12'},handleCodeInApp: true};awaitsendSignInLinkToEmail(auth,'user@example.com',actionCodeSettings);// Obtain emailLink from the user.if(isSignInWithEmailLink(auth,emailLink)){awaitsignInWithEmailLink(auth,'user@example.com',emailLink);}

signInWithPhoneNumber(auth, phoneNumber, appVerifier) {:#signinwithphonenumber_75b2560}

Asynchronously signs in using a phone number.

This method sends a code via SMS to the given phone number, and returns a ConfirmationResult. After the user provides the code sent to their phone, call ConfirmationResult.confirm() with the code to sign the user in.

For abuse prevention, this method requires a ApplicationVerifier. This SDK includes an implementation based on reCAPTCHA v2, RecaptchaVerifier. This function can work on other platforms that do not support the RecaptchaVerifier (like React Native), but you need to use a third-party ApplicationVerifier implementation.

If you've enabled project-level reCAPTCHA Enterprise bot protection in Enforce mode, you can omit the ApplicationVerifier.

This method does not work in a Node.js environment or with Auth instances created with a FirebaseServerApp.

Signature:

exportdeclarefunctionsignInWithPhoneNumber(auth: Auth,phoneNumber: string,appVerifier?: ApplicationVerifier): Promise<ConfirmationResult>;

Parameters

ParameterTypeDescription
authAuthThe Auth instance.
phoneNumberstringThe user's phone number in E.164 format (e.g. +16505550101).
appVerifierApplicationVerifierThe ApplicationVerifier.

Returns:

Promise<ConfirmationResult>

Example

// 'recaptcha-container' is the ID of an element in the DOM.constapplicationVerifier=newfirebase.auth.RecaptchaVerifier('recaptcha-container');constconfirmationResult=awaitsignInWithPhoneNumber(auth,phoneNumber,applicationVerifier);// Obtain a verificationCode from the user.constcredential=awaitconfirmationResult.confirm(verificationCode);

signInWithPopup(auth, provider, resolver) {:#signinwithpopup_770f816}

Authenticates a Firebase client using a popup-based OAuth authentication flow.

If succeeds, returns the signed in user along with the provider's credential. If sign in was unsuccessful, returns an error object containing additional information about the error.

This method does not work in a Node.js environment or with Auth instances created with a FirebaseServerApp.

Signature:

exportdeclarefunctionsignInWithPopup(auth: Auth,provider: AuthProvider,resolver?: PopupRedirectResolver): Promise<UserCredential>;

Parameters

ParameterTypeDescription
authAuthThe Auth instance.
providerAuthProviderThe provider to authenticate. The provider has to be an OAuthProvider. Non-OAuth providers like EmailAuthProvider will throw an error.
resolverPopupRedirectResolverAn instance of PopupRedirectResolver, optional if already supplied to initializeAuth() or provided by getAuth().

Returns:

Promise<UserCredential>

Example

// Sign in using a popup.constprovider=newFacebookAuthProvider();constresult=awaitsignInWithPopup(auth,provider);// The signed-in user info.constuser=result.user;// This gives you a Facebook Access Token.constcredential=provider.credentialFromResult(auth,result);consttoken=credential.accessToken;

signInWithRedirect(auth, provider, resolver) {:#signinwithredirect_770f816}

Authenticates a Firebase client using a full-page redirect flow.

To handle the results and errors for this operation, refer to getRedirectResult(). Follow the best practices when using signInWithRedirect().

This method does not work in a Node.js environment or with Auth instances created with a FirebaseServerApp.

Signature:

exportdeclarefunctionsignInWithRedirect(auth: Auth,provider: AuthProvider,resolver?: PopupRedirectResolver): Promise<never>;

Parameters

ParameterTypeDescription
authAuthThe Auth instance.
providerAuthProviderThe provider to authenticate. The provider has to be an OAuthProvider. Non-OAuth providers like EmailAuthProvider will throw an error.
resolverPopupRedirectResolverAn instance of PopupRedirectResolver, optional if already supplied to initializeAuth() or provided by getAuth().

Returns:

Promise<never>

Example

// Sign in using a redirect.constprovider=newFacebookAuthProvider();// You can add additional scopes to the provider:provider.addScope('user_birthday');// Start a sign in process for an unauthenticated user.awaitsignInWithRedirect(auth,provider);// This will trigger a full page redirect away from your app// After returning from the redirect when your app initializes you can obtain the resultconstresult=awaitgetRedirectResult(auth);if(result){// This is the signed-in userconstuser=result.user;// This gives you a Facebook Access Token.constcredential=provider.credentialFromResult(auth,result);consttoken=credential.accessToken;}// As this API can be used for sign-in, linking and reauthentication,// check the operationType to determine what triggered this redirect// operation.constoperationType=result.operationType;

signOut(auth) {:#signout_2a61ea7}

Signs out the current user.

This method is not supported by Auth instances created with a FirebaseServerApp.

Signature:

exportdeclarefunctionsignOut(auth: Auth): Promise<void>;

Parameters

ParameterTypeDescription
authAuthThe Auth instance.

Returns:

Promise<void>

updateCurrentUser(auth, user) {:#updatecurrentuser_9d96fff}

Asynchronously sets the provided user as Auth.currentUser on the Auth instance.

A new instance copy of the user provided will be made and set as currentUser.

This will trigger onAuthStateChanged() and onIdTokenChanged() listeners like other sign in methods.

The operation fails with an error if the user to be updated belongs to a different Firebase project.

This method is not supported by Auth instances created with a FirebaseServerApp.

Signature:

exportdeclarefunctionupdateCurrentUser(auth: Auth,user: User|null): Promise<void>;

Parameters

ParameterTypeDescription
authAuthThe Auth instance.
userUser | nullThe new User.

Returns:

Promise<void>

useDeviceLanguage(auth) {:#usedevicelanguage_2a61ea7}

Sets the current language to the default device/browser preference.

Signature:

exportdeclarefunctionuseDeviceLanguage(auth: Auth): void;

Parameters

ParameterTypeDescription
authAuthThe Auth instance.

Returns:

void

validatePassword(auth, password) {:#validatepassword_4dc4ad2}

Validates the password against the password policy configured for the project or tenant.

If no tenant ID is set on the Auth instance, then this method will use the password policy configured for the project. Otherwise, this method will use the policy configured for the tenant. If a password policy has not been configured, then the default policy configured for all projects will be used.

If an auth flow fails because a submitted password does not meet the password policy requirements and this method has previously been called, then this method will use the most recent policy available when called again.

Signature:

exportdeclarefunctionvalidatePassword(auth: Auth,password: string): Promise<PasswordValidationStatus>;

Parameters

ParameterTypeDescription
authAuthThe Auth instance.
passwordstringThe password to validate.

Returns:

Promise<PasswordValidationStatus>

Example

validatePassword(auth,'some-password');

verifyPasswordResetCode(auth, code) {:#verifypasswordresetcode_01e0a1a}

Checks a password reset code sent to the user by email or other out-of-band mechanism.

Signature:

exportdeclarefunctionverifyPasswordResetCode(auth: Auth,code: string): Promise<string>;

Parameters

ParameterTypeDescription
authAuthThe Auth instance.
codestringA verification code sent to the user.

Returns:

Promise<string>

the user's email address if valid.

function(link, ...)

parseActionCodeURL(link) {:#parseactioncodeurl_51293c3}

Parses the email action link string and returns an ActionCodeURL if the link is valid, otherwise returns null.

Signature:

exportdeclarefunctionparseActionCodeURL(link: string): ActionCodeURL|null;

Parameters

ParameterTypeDescription
linkstring

Returns:

ActionCodeURL | null

function(user, ...)

deleteUser(user) {:#deleteuser_52b2e2e}

Deletes and signs out the user.

Important: this is a security-sensitive operation that requires the user to have recently signed in. If this requirement isn't met, ask the user to authenticate again and then call reauthenticateWithCredential().

Signature:

exportdeclarefunctiondeleteUser(user: User): Promise<void>;

Parameters

ParameterTypeDescription
userUserThe user.

Returns:

Promise<void>

getIdToken(user, forceRefresh) {:#getidtoken_ce7d429}

Returns a JSON Web Token (JWT) used to identify the user to a Firebase service.

Returns the current token if it has not expired or if it will not expire in the next five minutes. Otherwise, this will refresh the token and return a new one.

Signature:

exportdeclarefunctiongetIdToken(user: User,forceRefresh?: boolean): Promise<string>;

Parameters

ParameterTypeDescription
userUserThe user.
forceRefreshbooleanForce refresh regardless of token expiration.

Returns:

Promise<string>

getIdTokenResult(user, forceRefresh) {:#getidtokenresult_ce7d429}

Returns a deserialized JSON Web Token (JWT) used to identify the user to a Firebase service.

Returns the current token if it has not expired or if it will not expire in the next five minutes. Otherwise, this will refresh the token and return a new one.

Signature:

exportdeclarefunctiongetIdTokenResult(user: User,forceRefresh?: boolean): Promise<IdTokenResult>;

Parameters

ParameterTypeDescription
userUserThe user.
forceRefreshbooleanForce refresh regardless of token expiration.

Returns:

Promise<IdTokenResult>

linkWithCredential(user, credential) {:#linkwithcredential_60f8043}

Links the user account with the given credentials.

An AuthProvider can be used to generate the credential.

Signature:

exportdeclarefunctionlinkWithCredential(user: User,credential: AuthCredential): Promise<UserCredential>;

Parameters

ParameterTypeDescription
userUserThe user.
credentialAuthCredentialThe auth credential.

Returns:

Promise<UserCredential>

linkWithPhoneNumber(user, phoneNumber, appVerifier) {:#linkwithphonenumber_9ed75fe}

Links the user account with the given phone number.

This method does not work in a Node.js environment.

Signature:

exportdeclarefunctionlinkWithPhoneNumber(user: User,phoneNumber: string,appVerifier?: ApplicationVerifier): Promise<ConfirmationResult>;

Parameters

ParameterTypeDescription
userUserThe user.
phoneNumberstringThe user's phone number in E.164 format (e.g. +16505550101).
appVerifierApplicationVerifierThe ApplicationVerifier.

Returns:

Promise<ConfirmationResult>

linkWithPopup(user, provider, resolver) {:#linkwithpopup_41c0b31}

Links the authenticated provider to the user account using a pop-up based OAuth flow.

If the linking is successful, the returned result will contain the user and the provider's credential.

This method does not work in a Node.js environment.

Signature:

exportdeclarefunctionlinkWithPopup(user: User,provider: AuthProvider,resolver?: PopupRedirectResolver): Promise<UserCredential>;

Parameters

ParameterTypeDescription
userUserThe user.
providerAuthProviderThe provider to authenticate. The provider has to be an OAuthProvider. Non-OAuth providers like EmailAuthProvider will throw an error.
resolverPopupRedirectResolverAn instance of PopupRedirectResolver, optional if already supplied to initializeAuth() or provided by getAuth().

Returns:

Promise<UserCredential>

Example

// Sign in using some other provider.constresult=awaitsignInWithEmailAndPassword(auth,email,password);// Link using a popup.constprovider=newFacebookAuthProvider();awaitlinkWithPopup(result.user,provider);

linkWithRedirect(user, provider, resolver) {:#linkwithredirect_41c0b31}

Links the OAuthProvider to the user account using a full-page redirect flow.

To handle the results and errors for this operation, refer to getRedirectResult(). Follow the best practices when using linkWithRedirect().

This method does not work in a Node.js environment or with Auth instances created with a FirebaseServerApp.

Signature:

exportdeclarefunctionlinkWithRedirect(user: User,provider: AuthProvider,resolver?: PopupRedirectResolver): Promise<never>;

Parameters

ParameterTypeDescription
userUserThe user.
providerAuthProviderThe provider to authenticate. The provider has to be an OAuthProvider. Non-OAuth providers like EmailAuthProvider will throw an error.
resolverPopupRedirectResolverAn instance of PopupRedirectResolver, optional if already supplied to initializeAuth() or provided by getAuth().

Returns:

Promise<never>

Example

// Sign in using some other provider.constresult=awaitsignInWithEmailAndPassword(auth,email,password);// Link using a redirect.constprovider=newFacebookAuthProvider();awaitlinkWithRedirect(result.user,provider);// This will trigger a full page redirect away from your app// After returning from the redirect when your app initializes you can obtain the resultconstresult=awaitgetRedirectResult(auth);

multiFactor(user) {:#multifactor_52b2e2e}

The MultiFactorUser corresponding to the user.

This is used to access all multi-factor properties and operations related to the user.

Signature:

exportdeclarefunctionmultiFactor(user: User): MultiFactorUser;

Parameters

ParameterTypeDescription
userUserThe user.

Returns:

MultiFactorUser

reauthenticateWithCredential(user, credential) {:#reauthenticatewithcredential_60f8043}

Re-authenticates a user using a fresh credential.

Use before operations such as updatePassword() that require tokens from recent sign-in attempts. This method can be used to recover from a CREDENTIAL_TOO_OLD_LOGIN_AGAIN error or a TOKEN_EXPIRED error.

This method is not supported on any User signed in by Auth instances created with a FirebaseServerApp.

Signature:

exportdeclarefunctionreauthenticateWithCredential(user: User,credential: AuthCredential): Promise<UserCredential>;

Parameters

ParameterTypeDescription
userUserThe user.
credentialAuthCredentialThe auth credential.

Returns:

Promise<UserCredential>

reauthenticateWithPhoneNumber(user, phoneNumber, appVerifier) {:#reauthenticatewithphonenumber_9ed75fe}

Re-authenticates a user using a fresh phone credential.

Use before operations such as updatePassword() that require tokens from recent sign-in attempts.

This method does not work in a Node.js environment or on any User signed in by Auth instances created with a FirebaseServerApp.

Signature:

exportdeclarefunctionreauthenticateWithPhoneNumber(user: User,phoneNumber: string,appVerifier?: ApplicationVerifier): Promise<ConfirmationResult>;

Parameters

ParameterTypeDescription
userUserThe user.
phoneNumberstringThe user's phone number in E.164 format (e.g. +16505550101).
appVerifierApplicationVerifierThe ApplicationVerifier.

Returns:

Promise<ConfirmationResult>

reauthenticateWithPopup(user, provider, resolver) {:#reauthenticatewithpopup_41c0b31}

Reauthenticates the current user with the specified OAuthProvider using a pop-up based OAuth flow.

If the reauthentication is successful, the returned result will contain the user and the provider's credential.

This method does not work in a Node.js environment or on any User signed in by Auth instances created with a FirebaseServerApp.

Signature:

exportdeclarefunctionreauthenticateWithPopup(user: User,provider: AuthProvider,resolver?: PopupRedirectResolver): Promise<UserCredential>;

Parameters

ParameterTypeDescription
userUserThe user.
providerAuthProviderThe provider to authenticate. The provider has to be an OAuthProvider. Non-OAuth providers like EmailAuthProvider will throw an error.
resolverPopupRedirectResolverAn instance of PopupRedirectResolver, optional if already supplied to initializeAuth() or provided by getAuth().

Returns:

Promise<UserCredential>

Example

// Sign in using a popup.constprovider=newFacebookAuthProvider();constresult=awaitsignInWithPopup(auth,provider);// Reauthenticate using a popup.awaitreauthenticateWithPopup(result.user,provider);

reauthenticateWithRedirect(user, provider, resolver) {:#reauthenticatewithredirect_41c0b31}

Reauthenticates the current user with the specified OAuthProvider using a full-page redirect flow.

To handle the results and errors for this operation, refer to getRedirectResult(). Follow the best practices when using reauthenticateWithRedirect().

This method does not work in a Node.js environment or with Auth instances created with a FirebaseServerApp.

Signature:

exportdeclarefunctionreauthenticateWithRedirect(user: User,provider: AuthProvider,resolver?: PopupRedirectResolver): Promise<never>;

Parameters

ParameterTypeDescription
userUserThe user.
providerAuthProviderThe provider to authenticate. The provider has to be an OAuthProvider. Non-OAuth providers like EmailAuthProvider will throw an error.
resolverPopupRedirectResolverAn instance of PopupRedirectResolver, optional if already supplied to initializeAuth() or provided by getAuth().

Returns:

Promise<never>

Example

// Sign in using a redirect.constprovider=newFacebookAuthProvider();constresult=awaitsignInWithRedirect(auth,provider);// This will trigger a full page redirect away from your app// After returning from the redirect when your app initializes you can obtain the resultconstresult=awaitgetRedirectResult(auth);// Reauthenticate using a redirect.awaitreauthenticateWithRedirect(result.user,provider);// This will again trigger a full page redirect away from your app// After returning from the redirect when your app initializes you can obtain the resultconstresult=awaitgetRedirectResult(auth);

reload(user) {:#reload_52b2e2e}

Reloads user account data, if signed in.

Signature:

exportdeclarefunctionreload(user: User): Promise<void>;

Parameters

ParameterTypeDescription
userUserThe user.

Returns:

Promise<void>

sendEmailVerification(user, actionCodeSettings) {:#sendemailverification_6a885d6}

Sends a verification email to a user.

The verification process is completed by calling applyActionCode().

Signature:

exportdeclarefunctionsendEmailVerification(user: User,actionCodeSettings?: ActionCodeSettings|null): Promise<void>;

Parameters

ParameterTypeDescription
userUserThe user.
actionCodeSettingsActionCodeSettings | nullThe ActionCodeSettings.

Returns:

Promise<void>

Example

constactionCodeSettings={url: 'https://www.example.com/?email=user@example.com',iOS: {bundleId: 'com.example.ios'},android: {packageName: 'com.example.android',installApp: true,minimumVersion: '12'},handleCodeInApp: true};awaitsendEmailVerification(user,actionCodeSettings);// Obtain code from the user.awaitapplyActionCode(auth,code);

unlink(user, providerId) {:#unlink_f289a14}

Unlinks a provider from a user account.

Signature:

exportdeclarefunctionunlink(user: User,providerId: string): Promise<User>;

Parameters

ParameterTypeDescription
userUserThe user.
providerIdstringThe provider to unlink.

Returns:

Promise<User>

updateEmail(user, newEmail) {:#updateemail_7737d57}

Updates the user's email address.

An email will be sent to the original email address (if it was set) that allows to revoke the email address change, in order to protect them from account hijacking.

This method is not supported on any User signed in by Auth instances created with a FirebaseServerApp.

Important: this is a security sensitive operation that requires the user to have recently signed in. If this requirement isn't met, ask the user to authenticate again and then call reauthenticateWithCredential().

Signature:

exportdeclarefunctionupdateEmail(user: User,newEmail: string): Promise<void>;

Parameters

ParameterTypeDescription
userUserThe user.
newEmailstringThe new email address.Throws "auth/operation-not-allowed" error when Email Enumeration Protection is enabled. Deprecated - Use verifyBeforeUpdateEmail() instead.

Returns:

Promise<void>

updatePassword(user, newPassword) {:#updatepassword_6df673e}

Updates the user's password.

Important: this is a security sensitive operation that requires the user to have recently signed in. If this requirement isn't met, ask the user to authenticate again and then call reauthenticateWithCredential().

Signature:

exportdeclarefunctionupdatePassword(user: User,newPassword: string): Promise<void>;

Parameters

ParameterTypeDescription
userUserThe user.
newPasswordstringThe new password.

Returns:

Promise<void>

updatePhoneNumber(user, credential) {:#updatephonenumber_0105c49}

Updates the user's phone number.

This method does not work in a Node.js environment or on any User signed in by Auth instances created with a FirebaseServerApp.

Signature:

exportdeclarefunctionupdatePhoneNumber(user: User,credential: PhoneAuthCredential): Promise<void>;

Parameters

ParameterTypeDescription
userUserThe user.
credentialPhoneAuthCredentialA credential authenticating the new phone number.

Returns:

Promise<void>

Example

// 'recaptcha-container' is the ID of an element in the DOM. const applicationVerifier = new RecaptchaVerifier('recaptcha-container'); const provider = new PhoneAuthProvider(auth); const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier); // Obtain the verificationCode from the user. const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode); await updatePhoneNumber(user, phoneCredential); 

updateProfile(user, { displayName, photoURL: photoUrl }) {:#updateprofile_017e12d}

Updates a user's profile data.

Signature:

exportdeclarefunctionupdateProfile(user: User,{ displayName,photoURL: photoUrl}: {displayName?: string|null;photoURL?: string|null;}): Promise<void>;

Parameters

ParameterTypeDescription
userUserThe user.
{ displayName, photoURL: photoUrl }{ displayName?: string | null; photoURL?: string | null; }

Returns:

Promise<void>

verifyBeforeUpdateEmail(user, newEmail, actionCodeSettings) {:#verifybeforeupdateemail_09d6f11}

Sends a verification email to a new email address.

The user's email will be updated to the new one after being verified.

If you have a custom email action handler, you can complete the verification process by calling applyActionCode().

Signature:

exportdeclarefunctionverifyBeforeUpdateEmail(user: User,newEmail: string,actionCodeSettings?: ActionCodeSettings|null): Promise<void>;

Parameters

ParameterTypeDescription
userUserThe user.
newEmailstringThe new email address to be verified before update.
actionCodeSettingsActionCodeSettings | nullThe ActionCodeSettings.

Returns:

Promise<void>

Example

constactionCodeSettings={url: 'https://www.example.com/?email=user@example.com',iOS: {bundleId: 'com.example.ios'},android: {packageName: 'com.example.android',installApp: true,minimumVersion: '12'},handleCodeInApp: true};awaitverifyBeforeUpdateEmail(user,'newemail@example.com',actionCodeSettings);// Obtain code from the user.awaitapplyActionCode(auth,code);

function(userCredential, ...)

getAdditionalUserInfo(userCredential) {:#getadditionaluserinfo_838a6bd}

Extracts provider specific AdditionalUserInfo for the given credential.

Signature:

exportdeclarefunctiongetAdditionalUserInfo(userCredential: UserCredential): AdditionalUserInfo|null;

Parameters

ParameterTypeDescription
userCredentialUserCredentialThe user credential.

Returns:

AdditionalUserInfo | null

ActionCodeOperation

An enumeration of the possible email action types.

Signature:

ActionCodeOperation: { readonly EMAIL_SIGNIN: "EMAIL_SIGNIN";readonly PASSWORD_RESET: "PASSWORD_RESET";readonly RECOVER_EMAIL: "RECOVER_EMAIL";readonly REVERT_SECOND_FACTOR_ADDITION: "REVERT_SECOND_FACTOR_ADDITION";readonly VERIFY_AND_CHANGE_EMAIL: "VERIFY_AND_CHANGE_EMAIL";readonly VERIFY_EMAIL: "VERIFY_EMAIL";}

AuthErrorCodes

A map of potential Auth error codes, for easier comparison with errors thrown by the SDK.

Note that you can't tree-shake individual keys in the map, so by using the map you might substantially increase your bundle size.

Signature:

AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY: { readonly ADMIN_ONLY_OPERATION: "auth/admin-restricted-operation";readonly ARGUMENT_ERROR: "auth/argument-error";readonly APP_NOT_AUTHORIZED: "auth/app-not-authorized";readonly APP_NOT_INSTALLED: "auth/app-not-installed";readonly CAPTCHA_CHECK_FAILED: "auth/captcha-check-failed";readonly CODE_EXPIRED: "auth/code-expired";readonly CORDOVA_NOT_READY: "auth/cordova-not-ready";readonly CORS_UNSUPPORTED: "auth/cors-unsupported";readonly CREDENTIAL_ALREADY_IN_USE: "auth/credential-already-in-use";readonly CREDENTIAL_MISMATCH: "auth/custom-token-mismatch";readonly CREDENTIAL_TOO_OLD_LOGIN_AGAIN: "auth/requires-recent-login";readonly DEPENDENT_SDK_INIT_BEFORE_AUTH: "auth/dependent-sdk-initialized-before-auth";readonly DYNAMIC_LINK_NOT_ACTIVATED: "auth/dynamic-link-not-activated";readonly EMAIL_CHANGE_NEEDS_VERIFICATION: "auth/email-change-needs-verification";readonly EMAIL_EXISTS: "auth/email-already-in-use";readonly EMULATOR_CONFIG_FAILED: "auth/emulator-config-failed";readonly EXPIRED_OOB_CODE: "auth/expired-action-code";readonly EXPIRED_POPUP_REQUEST: "auth/cancelled-popup-request";readonly INTERNAL_ERROR: "auth/internal-error";readonly INVALID_API_KEY: "auth/invalid-api-key";readonly INVALID_APP_CREDENTIAL: "auth/invalid-app-credential";readonly INVALID_APP_ID: "auth/invalid-app-id";readonly INVALID_AUTH: "auth/invalid-user-token";readonly INVALID_AUTH_EVENT: "auth/invalid-auth-event";readonly INVALID_CERT_HASH: "auth/invalid-cert-hash";readonly INVALID_CODE: "auth/invalid-verification-code";readonly INVALID_CONTINUE_URI: "auth/invalid-continue-uri";readonly INVALID_CORDOVA_CONFIGURATION: "auth/invalid-cordova-configuration";readonly INVALID_CUSTOM_TOKEN: "auth/invalid-custom-token";readonly INVALID_DYNAMIC_LINK_DOMAIN: "auth/invalid-dynamic-link-domain";readonly INVALID_EMAIL: "auth/invalid-email";readonly INVALID_EMULATOR_SCHEME: "auth/invalid-emulator-scheme";readonly INVALID_IDP_RESPONSE: "auth/invalid-credential";readonly INVALID_LOGIN_CREDENTIALS: "auth/invalid-credential";readonly INVALID_MESSAGE_PAYLOAD: "auth/invalid-message-payload";readonly INVALID_MFA_SESSION: "auth/invalid-multi-factor-session";readonly INVALID_OAUTH_CLIENT_ID: "auth/invalid-oauth-client-id";readonly INVALID_OAUTH_PROVIDER: "auth/invalid-oauth-provider";readonly INVALID_OOB_CODE: "auth/invalid-action-code";readonly INVALID_ORIGIN: "auth/unauthorized-domain";readonly INVALID_PASSWORD: "auth/wrong-password";readonly INVALID_PERSISTENCE: "auth/invalid-persistence-type";readonly INVALID_PHONE_NUMBER: "auth/invalid-phone-number";readonly INVALID_PROVIDER_ID: "auth/invalid-provider-id";readonly INVALID_RECIPIENT_EMAIL: "auth/invalid-recipient-email";readonly INVALID_SENDER: "auth/invalid-sender";readonly INVALID_SESSION_INFO: "auth/invalid-verification-id";readonly INVALID_TENANT_ID: "auth/invalid-tenant-id";readonly MFA_INFO_NOT_FOUND: "auth/multi-factor-info-not-found";readonly MFA_REQUIRED: "auth/multi-factor-auth-required";readonly MISSING_ANDROID_PACKAGE_NAME: "auth/missing-android-pkg-name";readonly MISSING_APP_CREDENTIAL: "auth/missing-app-credential";readonly MISSING_AUTH_DOMAIN: "auth/auth-domain-config-required";readonly MISSING_CODE: "auth/missing-verification-code";readonly MISSING_CONTINUE_URI: "auth/missing-continue-uri";readonly MISSING_IFRAME_START: "auth/missing-iframe-start";readonly MISSING_IOS_BUNDLE_ID: "auth/missing-ios-bundle-id";readonly MISSING_OR_INVALID_NONCE: "auth/missing-or-invalid-nonce";readonly MISSING_MFA_INFO: "auth/missing-multi-factor-info";readonly MISSING_MFA_SESSION: "auth/missing-multi-factor-session";readonly MISSING_PHONE_NUMBER: "auth/missing-phone-number";readonly MISSING_SESSION_INFO: "auth/missing-verification-id";readonly MODULE_DESTROYED: "auth/app-deleted";readonly NEED_CONFIRMATION: "auth/account-exists-with-different-credential";readonly NETWORK_REQUEST_FAILED: "auth/network-request-failed";readonly NULL_USER: "auth/null-user";readonly NO_AUTH_EVENT: "auth/no-auth-event";readonly NO_SUCH_PROVIDER: "auth/no-such-provider";readonly OPERATION_NOT_ALLOWED: "auth/operation-not-allowed";readonly OPERATION_NOT_SUPPORTED: "auth/operation-not-supported-in-this-environment";readonly POPUP_BLOCKED: "auth/popup-blocked";readonly POPUP_CLOSED_BY_USER: "auth/popup-closed-by-user";readonly PROVIDER_ALREADY_LINKED: "auth/provider-already-linked";readonly QUOTA_EXCEEDED: "auth/quota-exceeded";readonly REDIRECT_CANCELLED_BY_USER: "auth/redirect-cancelled-by-user";readonly REDIRECT_OPERATION_PENDING: "auth/redirect-operation-pending";readonly REJECTED_CREDENTIAL: "auth/rejected-credential";readonly SECOND_FACTOR_ALREADY_ENROLLED: "auth/second-factor-already-in-use";readonly SECOND_FACTOR_LIMIT_EXCEEDED: "auth/maximum-second-factor-count-exceeded";readonly TENANT_ID_MISMATCH: "auth/tenant-id-mismatch"; readonly TIMEOUT: "auth/timeout";readonly TOKEN_EXPIRED: "auth/user-token-expired";readonly TOO_MANY_ATTEMPTS_TRY_LATER: "auth/too-many-requests";readonly UNAUTHORIZED_DOMAIN: "auth/unauthorized-continue-uri";readonly UNSUPPORTED_FIRST_FACTOR: "auth/unsupported-first-factor";readonly UNSUPPORTED_PERSISTENCE: "auth/unsupported-persistence-type";readonly UNSUPPORTED_TENANT_OPERATION: "auth/unsupported-tenant-operation";readonly UNVERIFIED_EMAIL: "auth/unverified-email";readonly USER_CANCELLED: "auth/user-cancelled";readonly USER_DELETED: "auth/user-not-found";readonly USER_DISABLED: "auth/user-disabled";readonly USER_MISMATCH: "auth/user-mismatch";readonly USER_SIGNED_OUT: "auth/user-signed-out";readonly WEAK_PASSWORD: "auth/weak-password";readonly WEB_STORAGE_UNSUPPORTED: "auth/web-storage-unsupported";readonly ALREADY_INITIALIZED: "auth/already-initialized";readonly RECAPTCHA_NOT_ENABLED: "auth/recaptcha-not-enabled";readonly MISSING_RECAPTCHA_TOKEN: "auth/missing-recaptcha-token";readonly INVALID_RECAPTCHA_TOKEN: "auth/invalid-recaptcha-token";readonly INVALID_RECAPTCHA_ACTION: "auth/invalid-recaptcha-action";readonly MISSING_CLIENT_TYPE: "auth/missing-client-type";readonly MISSING_RECAPTCHA_VERSION: "auth/missing-recaptcha-version";readonly INVALID_RECAPTCHA_VERSION: "auth/invalid-recaptcha-version";readonly INVALID_REQ_TYPE: "auth/invalid-req-type";readonly INVALID_HOSTING_LINK_DOMAIN: "auth/invalid-hosting-link-domain";}

browserCookiePersistence

This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

An implementation of Persistence of type COOKIE, for use on the client side in applications leveraging hybrid rendering and middleware.

This persistence method requires companion middleware to function, such as that provided by ReactFire for NextJS.

Signature:

browserCookiePersistence: Persistence

browserLocalPersistence

An implementation of Persistence of type LOCAL using localStorage for the underlying storage.

Signature:

browserLocalPersistence: Persistence

browserPopupRedirectResolver

An implementation of PopupRedirectResolver suitable for browser based applications.

This method does not work in a Node.js environment.

Signature:

browserPopupRedirectResolver: PopupRedirectResolver

browserSessionPersistence

An implementation of Persistence of SESSION using sessionStorage for the underlying storage.

Signature:

browserSessionPersistence: Persistence

cordovaPopupRedirectResolver

An implementation of PopupRedirectResolver suitable for Cordova based applications.

Signature:

cordovaPopupRedirectResolver: PopupRedirectResolver

debugErrorMap

A verbose error map with detailed descriptions for most error codes.

See discussion at AuthErrorMap

Signature:

debugErrorMap: AuthErrorMap

FactorId

An enum of factors that may be used for multifactor authentication.

Signature:

FactorId: { readonly PHONE: "phone"; readonly TOTP: "totp";}

indexedDBLocalPersistence

An implementation of Persistence of type LOCAL using indexedDB for the underlying storage.

Signature:

indexedDBLocalPersistence: Persistence

inMemoryPersistence

An implementation of Persistence of type 'NONE'.

Signature:

inMemoryPersistence: Persistence

OperationType

Enumeration of supported operation types.

Signature:

OperationType: { readonly LINK: "link";readonly REAUTHENTICATE: "reauthenticate"; readonly SIGN_IN: "signIn";}

prodErrorMap

A minimal error map with all verbose error messages stripped.

See discussion at AuthErrorMap

Signature:

prodErrorMap: AuthErrorMap

ProviderId

Enumeration of supported providers.

Signature:

ProviderId: { readonly FACEBOOK: "facebook.com"; readonly GITHUB: "github.com"; readonly GOOGLE: "google.com";readonly PASSWORD: "password"; readonly PHONE: "phone"; readonly TWITTER: "twitter.com";}

SignInMethod

Enumeration of supported sign-in methods.

Signature:

SignInMethod: { readonly EMAIL_LINK: "emailLink";readonly EMAIL_PASSWORD: "password";readonly FACEBOOK: "facebook.com"; readonly GITHUB: "github.com"; readonly GOOGLE: "google.com"; readonly PHONE: "phone"; readonly TWITTER: "twitter.com";}

CustomParameters

Map of OAuth Custom Parameters.

Signature:

exporttypeCustomParameters=Record<string,string>;

NextOrObserver

Type definition for an event callback.

Signature:

exporttypeNextOrObserver<T>=NextFn<T|null>|Observer<T|null>;

PhoneInfoOptions

The information required to verify the ownership of a phone number.

The information that's required depends on whether you are doing single-factor sign-in, multi-factor enrollment or multi-factor sign-in.

Signature:

exporttypePhoneInfoOptions=PhoneSingleFactorInfoOptions|PhoneMultiFactorEnrollInfoOptions|PhoneMultiFactorSignInInfoOptions;

UserProfile

User profile used in AdditionalUserInfo.

Signature:

exporttypeUserProfile=Record<string,unknown>;
close