firebase
- Version 11.1.0
- Published
- 24.5 MB
- 28 dependencies
- Apache-2.0 license
Install
npm i firebase
yarn add firebase
pnpm add firebase
Overview
Firebase JavaScript library for web and Node.js
Index
Namespaces
firebase
- analytics()
- app()
- appCheck()
- apps
- auth()
- CompleteFn
- database()
- EmulatorMockTokenOptions
- ErrorFn
- FirebaseError
- FirebaseIdToken
- FirebaseSignInProvider
- firestore()
- functions()
- initializeApp()
- LogLevel
- messaging()
- NextFn
- Observer
- onLog()
- performance()
- registerVersion()
- remoteConfig()
- SDK_VERSION
- setLogLevel()
- storage()
- Unsubscribe
- User
- UserInfo
firebase.auth
- ActionCodeInfo
- ActionCodeSettings
- ActionCodeURL
- AdditionalUserInfo
- ApplicationVerifier
- Auth
- AuthCredential
- AuthError
- AuthProvider
- AuthSettings
- Config
- ConfirmationResult
- EmailAuthProvider
- EmailAuthProvider_Instance
- EmulatorConfig
- Error
- FacebookAuthProvider
- FacebookAuthProvider_Instance
- GithubAuthProvider
- GithubAuthProvider_Instance
- GoogleAuthProvider
- GoogleAuthProvider_Instance
- IdTokenResult
- MultiFactorAssertion
- MultiFactorError
- MultiFactorInfo
- MultiFactorResolver
- MultiFactorSession
- OAuthCredential
- OAuthCredentialOptions
- OAuthProvider
- PhoneAuthCredential
- PhoneAuthProvider
- PhoneAuthProvider_Instance
- PhoneInfoOptions
- PhoneMultiFactorAssertion
- PhoneMultiFactorEnrollInfoOptions
- PhoneMultiFactorGenerator
- PhoneMultiFactorInfo
- PhoneMultiFactorSignInInfoOptions
- PhoneSingleFactorInfoOptions
- RecaptchaVerifier
- RecaptchaVerifier_Instance
- SAMLAuthProvider
- TwitterAuthProvider
- TwitterAuthProvider_Instance
- UserCredential
- UserMetadata
firebase.firestore
- Blob
- CACHE_SIZE_UNLIMITED
- CollectionReference
- DocumentChange
- DocumentChangeType
- DocumentData
- DocumentReference
- DocumentSnapshot
- EmulatorMockTokenOptions
- FieldPath
- FieldValue
- Firestore
- FirestoreDataConverter
- FirestoreError
- FirestoreErrorCode
- GeoPoint
- GetOptions
- LoadBundleTask
- LoadBundleTaskProgress
- LogLevel
- OrderByDirection
- PersistenceSettings
- Query
- QueryDocumentSnapshot
- QuerySnapshot
- setLogLevel()
- SetOptions
- Settings
- SnapshotListenOptions
- SnapshotMetadata
- SnapshotOptions
- TaskState
- Timestamp
- Transaction
- UpdateData
- WhereFilterOp
- WriteBatch
Namespaces
namespace firebase
namespace firebase {}
firebase is a global namespace from which all Firebase services are accessed.
variable apps
var apps: app.App[];
A (read-only) array of all initialized apps.
variable SDK_VERSION
var SDK_VERSION: string;
The current SDK version.
function analytics
analytics: typeof analytics;
Gets the service.
firebase.analytics()
can be called with no arguments to access the default app's service.The Analytics SDK does not work in a Node.js environment.
Parameter app
The app to create an analytics service for. If not passed, uses the default app.
Example 1
// Get the Analytics service for the default appconst defaultAnalytics = firebase.analytics();
function app
app: (name?: string) => app.App;
Retrieves a Firebase instance.
When called with no arguments, the default app is returned. When an app name is provided, the app corresponding to that name is returned.
An exception is thrown if the app being retrieved has not yet been initialized.
Parameter name
Optional name of the app to return. If no name is provided, the default is
"[DEFAULT]"
.The app corresponding to the provided app name. If no app name is provided, the default app is returned.
Example 1
// Return the default appvar app = firebase.app();Example 2
// Return a named appvar otherApp = firebase.app("otherApp");
function appCheck
appCheck: typeof appCheck;
function auth
auth: typeof auth;
Gets the service for the default app or a given app.
firebase.auth()
can be called with no arguments to access the default app's service or asfirebase.auth(app)
to access the service associated with a specific app.Parameter app
Example 1
// Get the Auth service for the default appvar defaultAuth = firebase.auth();Example 2
// Get the Auth service for a given appvar otherAuth = firebase.auth(otherApp);
function database
database: typeof database;
Gets the service for the default app or a given app.
firebase.database()
can be called with no arguments to access the default app's service or asfirebase.database(app)
to access the service associated with a specific app.firebase.database
is also a namespace that can be used to access global constants and methods associated with theDatabase
service.Parameter app
Optional app whose Database service to return. If not provided, the default Database service will be returned. The default Database service if no app is provided or the Database service associated with the provided app.
Example 1
// Get the Database service for the default appvar defaultDatabase = firebase.database();Example 2
// Get the Database service for a specific appvar otherDatabase = firebase.database(app);
function firestore
firestore: typeof firestore;
function functions
functions: typeof functions;
function initializeApp
initializeApp: (options: Object, name?: string) => app.App;
Creates and initializes a Firebase instance.
See and for detailed documentation.
Parameter options
Options to configure the app's services.
Parameter name
Optional name of the app to initialize. If no name is provided, the default is
"[DEFAULT]"
.{!firebase.app.App} The initialized app.
Example 1
// Initialize default app// Retrieve your own options values by adding a web app on// https://console.firebase.google.comfirebase.initializeApp({apiKey: "AIza....", // Auth / General UseappId: "1:27992087142:web:ce....", // General UseprojectId: "my-firebase-project", // General UseauthDomain: "YOUR_APP.firebaseapp.com", // Auth with popup/redirectdatabaseURL: "https://YOUR_APP.firebaseio.com", // Realtime DatabasestorageBucket: "YOUR_APP.appspot.com", // StoragemessagingSenderId: "123456789", // Cloud MessagingmeasurementId: "G-12345" // Analytics});Example 2
// Initialize another appvar otherApp = firebase.initializeApp({apiKey: "AIza....",appId: "1:27992087142:web:ce....",projectId: "my-firebase-project",databaseURL: "https://<OTHER_DATABASE_NAME>.firebaseio.com",storageBucket: "<OTHER_STORAGE_BUCKET>.appspot.com"}, "nameOfOtherApp");
function messaging
messaging: typeof messaging;
Gets the service for the default app or a given app.
firebase.messaging()
can be called with no arguments to access the default app's service or asfirebase.messaging(app)
to access the service associated with a specific app.Calling
firebase.messaging()
in a service worker results in Firebase generating notifications if the push message payload has anotification
parameter.The Messaging SDK does not work in a Node.js environment.
Parameter app
The app to create a Messaging service for. If not passed, uses the default app.
Example 1
// Get the Messaging service for the default appvar defaultMessaging = firebase.messaging();Example 2
// Get the Messaging service for a given appvar otherMessaging = firebase.messaging(otherApp);
function onLog
onLog: ( logCallback: (callbackParams: { level: LogLevel; message: string; args: any[]; type: string; }) => void, options?: { level: LogLevel }) => void;
Sets log handler for all Firebase packages.
Parameter logCallback
An optional custom log handler that executes user code whenever the Firebase SDK makes a logging call.
function performance
performance: (app?: app.App) => performance.Performance;
Gets the service.
firebase.performance()
can be called with no arguments to access the default app's service. The service does not work with any other app.The Performance SDK does not work in a Node.js environment.
Parameter app
The app to create a performance service for. Performance Monitoring only works with the default app. If not passed, uses the default app.
Example 1
// Get the Performance service for the default appconst defaultPerformance = firebase.performance();
function registerVersion
registerVersion: (library: string, version: string, variant?: string) => void;
Registers a library's name and version for platform logging purposes.
Parameter library
Name of 1p or 3p library (e.g. firestore, angularfire)
Parameter version
Current version of that library.
Parameter variant
Bundle variant, e.g., node, rn, etc.
function remoteConfig
remoteConfig: typeof remoteConfig;
Gets the instance.
The Remote Config SDK does not work in a Node.js environment.
Parameter app
The app to create a Remote Config service for. If not passed, uses the default app.
Example 1
// Get the RemoteConfig instance for the default appconst defaultRemoteConfig = firebase.remoteConfig();
function setLogLevel
setLogLevel: (logLevel: LogLevel) => void;
Sets log level for all Firebase packages.
All of the log types above the current log level are captured (i.e. if you set the log level to
info
, errors are logged, butdebug
andverbose
logs are not).
function storage
storage: typeof storage;
Gets the service for the default app or a given app.
firebase.storage()
can be called with no arguments to access the default app's service or asfirebase.storage(app)
to access the service associated with a specific app.Parameter app
The app to create a storage service for. If not passed, uses the default app.
Example 1
// Get the Storage service for the default appvar defaultStorage = firebase.storage();Example 2
// Get the Storage service for a given appvar otherStorage = firebase.storage(otherApp);
interface FirebaseError
interface FirebaseError {}
FirebaseError
is a subclass of the standard JavaScriptError
object. In addition to a message string and stack trace, it contains a string code.
property code
code: string;
Error codes are strings using the following format:
"service/string-code"
. Some examples include"app/no-app"
and"auth/user-not-found"
.While the message for a given error can change, the code will remain the same between backward-compatible versions of the Firebase SDK.
property message
message: string;
An explanatory message for the error that just occurred.
This message is designed to be helpful to you, the developer. Because it generally does not convey meaningful information to end users, this message should not be displayed in your application.
property name
name: 'FirebaseError';
The name of the class of errors, which is
"FirebaseError"
.
property stack
stack?: string;
A string value containing the execution backtrace when the error originally occurred. This may not always be available.
When it is available, this information can be sent to to help explain the cause of an error.
interface FirebaseIdToken
interface FirebaseIdToken {}
property aud
aud: string;
Always set to PROJECT_ID
property auth_time
auth_time: number;
The time the user authenticated, normally 'iat'
property email
email?: string;
The user's primary email
property email_verified
email_verified?: boolean;
The user's email verification status
property exp
exp: number;
The token expiry time, normally 'iat' + 3600
property firebase
firebase: { /** The primary sign-in provider */ sign_in_provider: FirebaseSignInProvider;
/** A map of providers to the user's list of unique identifiers from each provider */ identities?: { [provider in FirebaseSignInProvider]?: string[] };};
Information on all identities linked to this user
property iat
iat: number;
The token issue time, in seconds since epoch
property iss
iss: string;
Always set to https://securetoken.google.com/PROJECT_ID
property name
name?: string;
The user's display name
property phone_number
phone_number?: string;
The user's primary phone number
property picture
picture?: string;
The user's profile photo URL
property provider_id
provider_id?: 'anonymous';
The sign in provider, only set when the provider is 'anonymous'
property sub
sub: string;
The user's unique ID
property uid
uid?: never;
property user_id
user_id: string;
The user's unique ID. Must be equal to 'sub'
index signature
[claim: string]: unknown;
Custom claims set by the developer
interface Observer
interface Observer<T, E = Error> {}
interface User
interface User extends firebase.UserInfo {}
A user account.
property emailVerified
emailVerified: boolean;
property isAnonymous
isAnonymous: boolean;
property metadata
metadata: firebase.auth.UserMetadata;
property multiFactor
multiFactor: firebase.User.MultiFactorUser;
The firebase.User.MultiFactorUser object corresponding to the current user. This is used to access all multi-factor properties and operations related to the current user.
property phoneNumber
phoneNumber: string | null;
The phone number normalized based on the E.164 standard (e.g. +16505550101) for the current user. This is null if the user has no phone credential linked to the account.
property providerData
providerData: (firebase.UserInfo | null)[];
property refreshToken
refreshToken: string;
property tenantId
tenantId: string | null;
The current user's tenant ID. This is a read-only property, which indicates the tenant ID used to sign in the current user. This is null if the user is signed in from the parent project.
Example 1
// Set the tenant ID on Auth instance.firebase.auth().tenantId = ‘TENANT_PROJECT_ID’;// All future sign-in request now include tenant ID.firebase.auth().signInWithEmailAndPassword(email, password).then(function(result) {// result.user.tenantId should be ‘TENANT_PROJECT_ID’.}).catch(function(error) {// Handle error.});
method delete
delete: () => Promise<void>;
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 firebase.User.reauthenticateWithCredential.
Error Codes auth/requires-recent-login Thrown if the user's last sign-in time does not meet the security threshold. Use firebase.User.reauthenticateWithCredential to resolve. This does not apply if the user is anonymous.
method getIdToken
getIdToken: (forceRefresh?: boolean) => Promise<string>;
Returns a JSON Web Token (JWT) used to identify the user to a Firebase service.
Returns the current token if it has not expired. Otherwise, this will refresh the token and return a new one.
Parameter forceRefresh
Force refresh regardless of token expiration.
method getIdTokenResult
getIdTokenResult: (forceRefresh?: boolean) => Promise<auth.IdTokenResult>;
method linkAndRetrieveDataWithCredential
linkAndRetrieveDataWithCredential: ( credential: auth.AuthCredential) => Promise<auth.UserCredential>;
Links the user account with the given credentials and returns any available additional user information, such as user name.
Error Codes auth/provider-already-linked Thrown if the provider has already been linked to the user. This error is thrown even if this is not the same provider's account that is currently linked to the user. auth/invalid-credential Thrown if the provider's credential is not valid. This can happen if it has already expired when calling link, or if it used invalid token(s). See the Firebase documentation for your provider, and make sure you pass in the correct parameters to the credential method. auth/credential-already-in-use Thrown if the account corresponding to the credential already exists among your users, or is already linked to a Firebase User. For example, this error could be thrown if you are upgrading an anonymous user to a Google user by linking a Google credential to it and the Google credential used is already associated with an existing Firebase Google user. The fields error.email, error.phoneNumber, and error.credential (firebase.auth.AuthCredential) may be provided, depending on the type of credential. You can recover from this error by signing in with error.credential directly via firebase.auth.Auth.signInWithCredential. auth/email-already-in-use Thrown if the email corresponding to the credential already exists among your users. When thrown while linking a credential to an existing user, an error.email and error.credential (firebase.auth.AuthCredential) fields are also provided. You have to link the credential to the existing user with that email if you wish to continue signing in with that credential. To do so, call firebase.auth.Auth.fetchSignInMethodsForEmail, sign in to error.email via one of the providers returned and then firebase.User.linkWithCredential the original credential to that newly signed in user. auth/operation-not-allowed Thrown if you have not enabled the provider in the Firebase Console. Go to the Firebase Console for your project, in the Auth section and the Sign in Method tab and configure the provider. auth/invalid-email Thrown if the email used in a firebase.auth.EmailAuthProvider.credential is invalid. auth/wrong-password Thrown if the password used in a firebase.auth.EmailAuthProvider.credential is not correct or when the user associated with the email does not have a password. auth/invalid-verification-code Thrown if the credential is a firebase.auth.PhoneAuthProvider.credential and the verification code of the credential is not valid. auth/invalid-verification-id Thrown if the credential is a firebase.auth.PhoneAuthProvider.credential and the verification ID of the credential is not valid.
Parameter credential
The auth credential.
Deprecated
This method is deprecated. Use firebase.User.linkWithCredential instead.
method linkWithCredential
linkWithCredential: ( credential: auth.AuthCredential) => Promise<auth.UserCredential>;
Links the user account with the given credentials.
Error Codes auth/provider-already-linked Thrown if the provider has already been linked to the user. This error is thrown even if this is not the same provider's account that is currently linked to the user. auth/invalid-credential Thrown if the provider's credential is not valid. This can happen if it has already expired when calling link, or if it used invalid token(s). See the Firebase documentation for your provider, and make sure you pass in the correct parameters to the credential method. auth/credential-already-in-use Thrown if the account corresponding to the credential already exists among your users, or is already linked to a Firebase User. For example, this error could be thrown if you are upgrading an anonymous user to a Google user by linking a Google credential to it and the Google credential used is already associated with an existing Firebase Google user. The fields error.email, error.phoneNumber, and error.credential (firebase.auth.AuthCredential) may be provided, depending on the type of credential. You can recover from this error by signing in with error.credential directly via firebase.auth.Auth.signInWithCredential. auth/email-already-in-use Thrown if the email corresponding to the credential already exists among your users. When thrown while linking a credential to an existing user, an error.email and error.credential (firebase.auth.AuthCredential) fields are also provided. You have to link the credential to the existing user with that email if you wish to continue signing in with that credential. To do so, call firebase.auth.Auth.fetchSignInMethodsForEmail, sign in to error.email via one of the providers returned and then firebase.User.linkWithCredential the original credential to that newly signed in user. auth/operation-not-allowed Thrown if you have not enabled the provider in the Firebase Console. Go to the Firebase Console for your project, in the Auth section and the Sign in Method tab and configure the provider. auth/invalid-email Thrown if the email used in a firebase.auth.EmailAuthProvider.credential is invalid. auth/wrong-password Thrown if the password used in a firebase.auth.EmailAuthProvider.credential is not correct or when the user associated with the email does not have a password. auth/invalid-verification-code Thrown if the credential is a firebase.auth.PhoneAuthProvider.credential and the verification code of the credential is not valid. auth/invalid-verification-id Thrown if the credential is a firebase.auth.PhoneAuthProvider.credential and the verification ID of the credential is not valid.
Parameter credential
The auth credential.
method linkWithPhoneNumber
linkWithPhoneNumber: ( phoneNumber: string, applicationVerifier: auth.ApplicationVerifier) => Promise<auth.ConfirmationResult>;
Links the user account with the given phone number.
Error Codes auth/provider-already-linked Thrown if the provider has already been linked to the user. This error is thrown even if this is not the same provider's account that is currently linked to the user. auth/captcha-check-failed Thrown if the reCAPTCHA response token was invalid, expired, or if this method was called from a non-whitelisted domain. auth/invalid-phone-number Thrown if the phone number has an invalid format. auth/missing-phone-number Thrown if the phone number is missing. auth/quota-exceeded Thrown if the SMS quota for the Firebase project has been exceeded. auth/user-disabled Thrown if the user corresponding to the given phone number has been disabled. auth/credential-already-in-use Thrown if the account corresponding to the phone number already exists among your users, or is already linked to a Firebase User. The fields error.phoneNumber and error.credential (firebase.auth.AuthCredential) are provided in this case. You can recover from this error by signing in with that credential directly via firebase.auth.Auth.signInWithCredential. auth/operation-not-allowed Thrown if you have not enabled the phone authentication provider in the Firebase Console. Go to the Firebase Console for your project, in the Auth section and the Sign in Method tab and configure the provider.
Parameter phoneNumber
The user's phone number in E.164 format (e.g. +16505550101).
Parameter applicationVerifier
method linkWithPopup
linkWithPopup: (provider: auth.AuthProvider) => Promise<auth.UserCredential>;
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.
Error Codes auth/auth-domain-config-required Thrown if authDomain configuration is not provided when calling firebase.initializeApp(). Check Firebase Console for instructions on determining and passing that field. auth/cancelled-popup-request Thrown if successive popup operations are triggered. Only one popup request is allowed at one time on a user or an auth instance. All the popups would fail with this error except for the last one. auth/credential-already-in-use Thrown if the account corresponding to the credential already exists among your users, or is already linked to a Firebase User. For example, this error could be thrown if you are upgrading an anonymous user to a Google user by linking a Google credential to it and the Google credential used is already associated with an existing Firebase Google user. An error.email and error.credential (firebase.auth.AuthCredential) fields are also provided. You can recover from this error by signing in with that credential directly via firebase.auth.Auth.signInWithCredential. auth/email-already-in-use Thrown if the email corresponding to the credential already exists among your users. When thrown while linking a credential to an existing user, an error.email and error.credential (firebase.auth.AuthCredential) fields are also provided. You have to link the credential to the existing user with that email if you wish to continue signing in with that credential. To do so, call firebase.auth.Auth.fetchSignInMethodsForEmail, sign in to error.email via one of the providers returned and then firebase.User.linkWithCredential the original credential to that newly signed in user. auth/operation-not-allowed Thrown if you have not enabled the provider in the Firebase Console. Go to the Firebase Console for your project, in the Auth section and the Sign in Method tab and configure the provider. auth/popup-blocked auth/operation-not-supported-in-this-environment Thrown if this operation is not supported in the environment your application is running on. "location.protocol" must be http or https. Thrown if the popup was blocked by the browser, typically when this operation is triggered outside of a click handler. auth/popup-closed-by-user Thrown if the popup window is closed by the user without completing the sign in to the provider. auth/provider-already-linked Thrown if the provider has already been linked to the user. This error is thrown even if this is not the same provider's account that is currently linked to the user. auth/unauthorized-domain Thrown if the app domain is not authorized for OAuth operations for your Firebase project. Edit the list of authorized domains from the Firebase console.
This method does not work in a Node.js environment.
Parameter provider
The provider to authenticate. The provider has to be an OAuth provider. Non-OAuth providers like firebase.auth.EmailAuthProvider will throw an error.
Example 1
// Creates the provider object.var provider = new firebase.auth.FacebookAuthProvider();// You can add additional scopes to the provider:provider.addScope('email');provider.addScope('user_friends');// Link with popup:user.linkWithPopup(provider).then(function(result) {// The firebase.User instance:var user = result.user;// The Facebook firebase.auth.AuthCredential containing the Facebook// access token:var credential = result.credential;}, function(error) {// An error happened.});
method linkWithRedirect
linkWithRedirect: (provider: auth.AuthProvider) => Promise<void>;
Links the authenticated provider to the user account using a full-page redirect flow.
Error Codes auth/auth-domain-config-required Thrown if authDomain configuration is not provided when calling firebase.initializeApp(). Check Firebase Console for instructions on determining and passing that field. auth/operation-not-supported-in-this-environment Thrown if this operation is not supported in the environment your application is running on. "location.protocol" must be http or https. auth/provider-already-linked Thrown if the provider has already been linked to the user. This error is thrown even if this is not the same provider's account that is currently linked to the user. auth/unauthorized-domain Thrown if the app domain is not authorized for OAuth operations for your Firebase project. Edit the list of authorized domains from the Firebase console.
Parameter provider
The provider to authenticate. The provider has to be an OAuth provider. Non-OAuth providers like firebase.auth.EmailAuthProvider will throw an error.
method reauthenticateAndRetrieveDataWithCredential
reauthenticateAndRetrieveDataWithCredential: ( credential: auth.AuthCredential) => Promise<auth.UserCredential>;
Re-authenticates a user using a fresh credential, and returns any available additional user information, such as user name. Use before operations such as firebase.User.updatePassword that require tokens from recent sign-in attempts.
Error Codes auth/user-mismatch Thrown if the credential given does not correspond to the user. auth/user-not-found Thrown if the credential given does not correspond to any existing user. auth/invalid-credential Thrown if the provider's credential is not valid. This can happen if it has already expired when calling link, or if it used invalid token(s). See the Firebase documentation for your provider, and make sure you pass in the correct parameters to the credential method. auth/invalid-email Thrown if the email used in a firebase.auth.EmailAuthProvider.credential is invalid. auth/wrong-password Thrown if the password used in a firebase.auth.EmailAuthProvider.credential is not correct or when the user associated with the email does not have a password. auth/invalid-verification-code Thrown if the credential is a firebase.auth.PhoneAuthProvider.credential and the verification code of the credential is not valid. auth/invalid-verification-id Thrown if the credential is a firebase.auth.PhoneAuthProvider.credential and the verification ID of the credential is not valid.
Parameter credential
Deprecated
This method is deprecated. Use firebase.User.reauthenticateWithCredential instead.
method reauthenticateWithCredential
reauthenticateWithCredential: ( credential: auth.AuthCredential) => Promise<auth.UserCredential>;
Re-authenticates a user using a fresh credential. Use before operations such as firebase.User.updatePassword that require tokens from recent sign-in attempts.
Error Codes auth/user-mismatch Thrown if the credential given does not correspond to the user. auth/user-not-found Thrown if the credential given does not correspond to any existing user. auth/invalid-credential Thrown if the provider's credential is not valid. This can happen if it has already expired when calling link, or if it used invalid token(s). See the Firebase documentation for your provider, and make sure you pass in the correct parameters to the credential method. auth/invalid-email Thrown if the email used in a firebase.auth.EmailAuthProvider.credential is invalid. auth/wrong-password Thrown if the password used in a firebase.auth.EmailAuthProvider.credential is not correct or when the user associated with the email does not have a password. auth/invalid-verification-code Thrown if the credential is a firebase.auth.PhoneAuthProvider.credential and the verification code of the credential is not valid. auth/invalid-verification-id Thrown if the credential is a firebase.auth.PhoneAuthProvider.credential and the verification ID of the credential is not valid.
Parameter credential
method reauthenticateWithPhoneNumber
reauthenticateWithPhoneNumber: ( phoneNumber: string, applicationVerifier: auth.ApplicationVerifier) => Promise<auth.ConfirmationResult>;
Re-authenticates a user using a fresh credential. Use before operations such as firebase.User.updatePassword that require tokens from recent sign-in attempts.
Error Codes auth/user-mismatch Thrown if the credential given does not correspond to the user. auth/user-not-found Thrown if the credential given does not correspond to any existing user. auth/captcha-check-failed Thrown if the reCAPTCHA response token was invalid, expired, or if this method was called from a non-whitelisted domain. auth/invalid-phone-number Thrown if the phone number has an invalid format. auth/missing-phone-number Thrown if the phone number is missing. auth/quota-exceeded Thrown if the SMS quota for the Firebase project has been exceeded.
Parameter phoneNumber
The user's phone number in E.164 format (e.g. +16505550101).
Parameter applicationVerifier
method reauthenticateWithPopup
reauthenticateWithPopup: ( provider: auth.AuthProvider) => Promise<auth.UserCredential>;
Reauthenticates the current user with the specified provider using a pop-up based OAuth flow.
If the reauthentication is successful, the returned result will contain the user and the provider's credential.
Error Codes auth/auth-domain-config-required Thrown if authDomain configuration is not provided when calling firebase.initializeApp(). Check Firebase Console for instructions on determining and passing that field. auth/cancelled-popup-request Thrown if successive popup operations are triggered. Only one popup request is allowed at one time on a user or an auth instance. All the popups would fail with this error except for the last one. auth/user-mismatch Thrown if the credential given does not correspond to the user. auth/operation-not-allowed Thrown if you have not enabled the provider in the Firebase Console. Go to the Firebase Console for your project, in the Auth section and the Sign in Method tab and configure the provider. auth/popup-blocked Thrown if the popup was blocked by the browser, typically when this operation is triggered outside of a click handler. auth/operation-not-supported-in-this-environment Thrown if this operation is not supported in the environment your application is running on. "location.protocol" must be http or https. auth/popup-closed-by-user Thrown if the popup window is closed by the user without completing the sign in to the provider. auth/unauthorized-domain Thrown if the app domain is not authorized for OAuth operations for your Firebase project. Edit the list of authorized domains from the Firebase console.
This method does not work in a Node.js environment.
Parameter provider
The provider to authenticate. The provider has to be an OAuth provider. Non-OAuth providers like firebase.auth.EmailAuthProvider will throw an error.
Example 1
// Creates the provider object.var provider = new firebase.auth.FacebookAuthProvider();// You can add additional scopes to the provider:provider.addScope('email');provider.addScope('user_friends');// Reauthenticate with popup:user.reauthenticateWithPopup(provider).then(function(result) {// The firebase.User instance:var user = result.user;// The Facebook firebase.auth.AuthCredential containing the Facebook// access token:var credential = result.credential;}, function(error) {// An error happened.});
method reauthenticateWithRedirect
reauthenticateWithRedirect: (provider: auth.AuthProvider) => Promise<void>;
Reauthenticates the current user with the specified OAuth provider using a full-page redirect flow.
Error Codes auth/auth-domain-config-required Thrown if authDomain configuration is not provided when calling firebase.initializeApp(). Check Firebase Console for instructions on determining and passing that field. auth/operation-not-supported-in-this-environment Thrown if this operation is not supported in the environment your application is running on. "location.protocol" must be http or https. auth/user-mismatch Thrown if the credential given does not correspond to the user. auth/unauthorized-domain Thrown if the app domain is not authorized for OAuth operations for your Firebase project. Edit the list of authorized domains from the Firebase console.
This method does not work in a Node.js environment.
Parameter provider
The provider to authenticate. The provider has to be an OAuth provider. Non-OAuth providers like firebase.auth.EmailAuthProvider will throw an error.
method reload
reload: () => Promise<void>;
Refreshes the current user, if signed in.
method sendEmailVerification
sendEmailVerification: ( actionCodeSettings?: auth.ActionCodeSettings) => Promise<void>;
Sends a verification email to a user.
The verification process is completed by calling firebase.auth.Auth.applyActionCode
Error Codes auth/missing-android-pkg-name An Android package name must be provided if the Android app is required to be installed. auth/missing-continue-uri A continue URL must be provided in the request. auth/missing-ios-bundle-id An iOS bundle ID must be provided if an App Store ID is provided. auth/invalid-continue-uri The continue URL provided in the request is invalid. auth/unauthorized-continue-uri The domain of the continue URL is not whitelisted. Whitelist the domain in the Firebase console.
Parameter actionCodeSettings
The action code settings. If specified, the state/continue URL will be set as the "continueUrl" parameter in the email verification link. The default email verification landing page will use this to display a link to go back to the app if it is installed. If the actionCodeSettings is not specified, no URL is appended to the action URL. The state URL provided must belong to a domain that is whitelisted by the developer in the console. Otherwise an error will be thrown. Mobile app redirects will only be applicable if the developer configures and accepts the Firebase Dynamic Links terms of condition. The Android package name and iOS bundle ID will be respected only if they are configured in the same Firebase Auth project used.
Example 1
var actionCodeSettings = {url: 'https://www.example.com/cart?email=user@example.com&cartId=123',iOS: {bundleId: 'com.example.ios'},android: {packageName: 'com.example.android',installApp: true,minimumVersion: '12'},handleCodeInApp: true};firebase.auth().currentUser.sendEmailVerification(actionCodeSettings).then(function() {// Verification email sent.}).catch(function(error) {// Error occurred. Inspect error.code.});
method toJSON
toJSON: () => Object;
Returns a JSON-serializable representation of this object.
A JSON-serializable representation of this object.
method unlink
unlink: (providerId: string) => Promise<firebase.User>;
Unlinks a provider from a user account.
Error Codes auth/no-such-provider Thrown if the user does not have this provider linked or when the provider ID given does not exist.
Parameter providerId
method updateEmail
updateEmail: (newEmail: string) => Promise<void>;
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.
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 firebase.User.reauthenticateWithCredential.
Error Codes auth/invalid-email Thrown if the email used is invalid. auth/email-already-in-use Thrown if the email is already used by another user. auth/requires-recent-login Thrown if the user's last sign-in time does not meet the security threshold. Use firebase.User.reauthenticateWithCredential to resolve. This does not apply if the user is anonymous.
Parameter newEmail
The new email address.
method updatePassword
updatePassword: (newPassword: string) => Promise<void>;
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 firebase.User.reauthenticateWithCredential.
Error Codes auth/weak-password Thrown if the password is not strong enough. auth/requires-recent-login Thrown if the user's last sign-in time does not meet the security threshold. Use firebase.User.reauthenticateWithCredential to resolve. This does not apply if the user is anonymous.
Parameter newPassword
method updatePhoneNumber
updatePhoneNumber: (phoneCredential: auth.AuthCredential) => Promise<void>;
Updates the user's phone number.
Error Codes auth/invalid-verification-code Thrown if the verification code of the credential is not valid. auth/invalid-verification-id Thrown if the verification ID of the credential is not valid.
Parameter phoneCredential
method updateProfile
updateProfile: (profile: { displayName?: string | null; photoURL?: string | null;}) => Promise<void>;
Updates a user's profile data.
Parameter profile
The profile's displayName and photoURL to update.
Example 1
// Updates the user attributes:user.updateProfile({displayName: "Jane Q. User",photoURL: "https://example.com/jane-q-user/profile.jpg"}).then(function() {// Profile updated successfully!// "Jane Q. User"var displayName = user.displayName;// "https://example.com/jane-q-user/profile.jpg"var photoURL = user.photoURL;}, function(error) {// An error happened.});// Passing a null value will delete the current attribute's value, but not// passing a property won't change the current attribute's value:// Let's say we're using the same user than before, after the update.user.updateProfile({photoURL: null}).then(function() {// Profile updated successfully!// "Jane Q. User", hasn't changed.var displayName = user.displayName;// Now, this is null.var photoURL = user.photoURL;}, function(error) {// An error happened.});
method verifyBeforeUpdateEmail
verifyBeforeUpdateEmail: ( newEmail: string, actionCodeSettings?: auth.ActionCodeSettings) => Promise<void>;
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 firebase.auth.Auth.applyActionCode.
Error Codes auth/missing-android-pkg-name An Android package name must be provided if the Android app is required to be installed. auth/missing-continue-uri A continue URL must be provided in the request. auth/missing-ios-bundle-id An iOS bundle ID must be provided if an App Store ID is provided. auth/invalid-continue-uri The continue URL provided in the request is invalid. auth/unauthorized-continue-uri The domain of the continue URL is not whitelisted. Whitelist the domain in the Firebase console.
Parameter newEmail
The email address to be verified and updated to.
Parameter actionCodeSettings
The action code settings. If specified, the state/continue URL will be set as the "continueUrl" parameter in the email verification link. The default email verification landing page will use this to display a link to go back to the app if it is installed. If the actionCodeSettings is not specified, no URL is appended to the action URL. The state URL provided must belong to a domain that is whitelisted by the developer in the console. Otherwise an error will be thrown. Mobile app redirects will only be applicable if the developer configures and accepts the Firebase Dynamic Links terms of condition. The Android package name and iOS bundle ID will be respected only if they are configured in the same Firebase Auth project used.
Example 1
var actionCodeSettings = {url: 'https://www.example.com/cart?email=user@example.com&cartId=123',iOS: {bundleId: 'com.example.ios'},android: {packageName: 'com.example.android',installApp: true,minimumVersion: '12'},handleCodeInApp: true};firebase.auth().currentUser.verifyBeforeUpdateEmail('user@example.com', actionCodeSettings).then(function() {// Verification email sent.}).catch(function(error) {// Error occurred. Inspect error.code.});
interface UserInfo
interface UserInfo {}
User profile information, visible only to the Firebase project's apps.
property displayName
displayName: string | null;
property email
email: string | null;
property phoneNumber
phoneNumber: string | null;
property photoURL
photoURL: string | null;
property providerId
providerId: string;
property uid
uid: string;
The user's unique ID.
type CompleteFn
type CompleteFn = () => void;
type EmulatorMockTokenOptions
type EmulatorMockTokenOptions = ({ user_id: string } | { sub: string }) & Partial<FirebaseIdToken>;
type ErrorFn
type ErrorFn<E = Error> = (error: E) => void;
type FirebaseSignInProvider
type FirebaseSignInProvider = | 'custom' | 'email' | 'password' | 'phone' | 'anonymous' | 'google.com' | 'facebook.com' | 'github.com' | 'twitter.com' | 'microsoft.com' | 'apple.com';
type LogLevel
type LogLevel = 'debug' | 'verbose' | 'info' | 'warn' | 'error' | 'silent';
The JS SDK supports 5 log levels and also allows a user the ability to silence the logs altogether.
The order is as follows: silent < debug < verbose < info < warn < error
type NextFn
type NextFn<T> = (value: T) => void;
type Unsubscribe
type Unsubscribe = () => void;
namespace firebase.analytics
namespace firebase.analytics {}
function isSupported
isSupported: () => Promise<boolean>;
An async function that returns true if current browser context supports initialization of analytics module (
firebase.analytics()
).Returns false otherwise.
function settings
settings: (settings: SettingsOptions) => void;
Configures Firebase Analytics to use custom
gtag
ordataLayer
names. Intended to be used ifgtag.js
script has been installed on this page independently of Firebase Analytics, and is using non-default names for either thegtag
function or fordataLayer
. Must be called before callingfirebase.analytics()
or it won't have any effect.
interface Analytics
interface Analytics {}
The Firebase Analytics service interface.
Do not call this constructor directly. Instead, use .
property app
app: firebase.app.App;
The associated with the
Analytics
service instance.Example 1
var app = analytics.app;
method logEvent
logEvent: { ( eventName: 'add_payment_info', eventParams?: { [key: string]: any; coupon?: EventParams['coupon']; currency?: EventParams['currency']; items?: EventParams['items']; payment_type?: EventParams['payment_type']; value?: EventParams['value']; }, options?: AnalyticsCallOptions ): void; ( eventName: 'add_shipping_info', eventParams?: { [key: string]: any; coupon?: string; currency?: string; items?: Item[]; shipping_tier?: string; value?: number; }, options?: AnalyticsCallOptions ): void; ( eventName: 'add_to_cart' | 'add_to_wishlist' | 'remove_from_cart', eventParams?: { [key: string]: any; currency?: string; value?: number; items?: Item[]; }, options?: AnalyticsCallOptions ): void; ( eventName: 'begin_checkout', eventParams?: { [key: string]: any; currency?: string; coupon?: string; value?: number; items?: Item[]; }, options?: AnalyticsCallOptions ): void; ( eventName: 'checkout_progress', eventParams?: { [key: string]: any; currency?: string; coupon?: string; value?: number; items?: Item[]; checkout_step?: number; checkout_option?: string; }, options?: AnalyticsCallOptions ): void; ( eventName: 'exception', eventParams?: { [key: string]: any; description?: string; fatal?: boolean; }, options?: AnalyticsCallOptions ): void; ( eventName: 'generate_lead', eventParams?: { [key: string]: any; value?: number; currency?: string }, options?: AnalyticsCallOptions ): void; ( eventName: 'login', eventParams?: { [key: string]: any; method?: string }, options?: AnalyticsCallOptions ): void; ( eventName: 'page_view', eventParams?: { [key: string]: any; page_title?: string; page_location?: string; page_path?: string; }, options?: AnalyticsCallOptions ): void; ( eventName: 'purchase' | 'refund', eventParams?: { [key: string]: any; value?: number; currency?: string; transaction_id: string; tax?: Currency; shipping?: Currency; items?: Item[]; coupon?: string; affiliation?: string; }, options?: AnalyticsCallOptions ): void; ( eventName: 'screen_view', eventParams?: { [key: string]: any; firebase_screen: string; firebase_screen_class: string; }, options?: AnalyticsCallOptions ): void; ( eventName: 'search' | 'view_search_results', eventParams?: { [key: string]: any; search_term?: string }, options?: AnalyticsCallOptions ): void; ( eventName: 'select_content', eventParams?: { [key: string]: any; content_type?: string; item_id?: string; }, options?: AnalyticsCallOptions ): void; ( eventName: 'select_item', eventParams?: { [key: string]: any; items?: Item[]; item_list_name?: string; item_list_id?: string; }, options?: AnalyticsCallOptions ): void; ( eventName: 'select_promotion' | 'view_promotion', eventParams?: { [key: string]: any; items?: Item[]; promotion_id?: string; promotion_name?: string; }, options?: AnalyticsCallOptions ): void; ( eventName: 'set_checkout_option', eventParams?: { [key: string]: any; checkout_step?: number; checkout_option?: string; }, options?: AnalyticsCallOptions ): void; ( eventName: 'share', eventParams?: { [key: string]: any; method?: string; content_type?: string; item_id?: string; }, options?: AnalyticsCallOptions ): void; ( eventName: 'sign_up', eventParams?: { [key: string]: any; method?: string }, options?: AnalyticsCallOptions ): void; ( eventName: 'timing_complete', eventParams?: { [key: string]: any; name: string; value: number; event_category?: string; event_label?: string; }, options?: AnalyticsCallOptions ): void; ( eventName: 'view_cart' | 'view_item', eventParams?: { [key: string]: any; currency?: string; items?: Item[]; value?: number; }, options?: AnalyticsCallOptions ): void; ( eventName: 'view_item_list', eventParams?: { [key: string]: any; items?: Item[]; item_list_name?: string; item_list_id?: string; }, options?: AnalyticsCallOptions ): void; <T extends string>( eventName: CustomEventName<T>, eventParams?: { [key: string]: any }, options?: AnalyticsCallOptions ): void;};
Sends analytics event with given
eventParams
. This method automatically associates this logged event with this Firebase web app instance on this device. List of recommended event parameters can be found in the GA4 reference documentation.Sends analytics event with given
eventParams
. This method automatically associates this logged event with this Firebase web app instance on this device. See Measure exceptions.Sends analytics event with given
eventParams
. This method automatically associates this logged event with this Firebase web app instance on this device. See Page views.Sends analytics event with given
eventParams
. This method automatically associates this logged event with this Firebase web app instance on this device. See Track Screenviews.
method setAnalyticsCollectionEnabled
setAnalyticsCollectionEnabled: (enabled: boolean) => void;
Sets whether analytics collection is enabled for this app on this device. window['ga-disable-analyticsId'] = true;
method setCurrentScreen
setCurrentScreen: (screenName: string, options?: AnalyticsCallOptions) => void;
Use gtag 'config' command to set 'screen_name'.
Deprecated
Use logEvent with
eventName
as 'screen_view' and add relevanteventParams
. See Track Screenviews.
method setUserId
setUserId: (id: string, options?: AnalyticsCallOptions) => void;
Use gtag 'config' command to set 'user_id'.
method setUserProperties
setUserProperties: ( properties: CustomParams, options?: AnalyticsCallOptions) => void;
Use gtag 'config' command to set all params specified.
interface AnalyticsCallOptions
interface AnalyticsCallOptions {}
Additional options that can be passed to Firebase Analytics method calls such as
logEvent
,setCurrentScreen
, etc.
property global
global: boolean;
If true, this config or event call applies globally to all analytics properties on the page.
interface ControlParams
interface ControlParams {}
Standard gtag.js control parameters. For more information, see .
property event_callback
event_callback?: () => void;
property event_timeout
event_timeout?: number;
property groups
groups?: string | string[];
property send_to
send_to?: string | string[];
interface CustomParams
interface CustomParams {}
Any custom params the user may pass to gtag.js.
index signature
[key: string]: any;
interface EventParams
interface EventParams {}
Standard gtag.js event parameters. For more information, see .
property affiliation
affiliation?: string;
property checkout_option
checkout_option?: string;
property checkout_step
checkout_step?: number;
property content_type
content_type?: string;
property coupon
coupon?: string;
property currency
currency?: string;
property description
description?: string;
property event_category
event_category: string;
property event_label
event_label?: string;
property fatal
fatal?: boolean;
property firebase_screen
firebase_screen?: string;
Firebase-specific. Use to log a
screen_name
to Firebase Analytics.
property firebase_screen_class
firebase_screen_class?: string;
Firebase-specific. Use to log a
screen_class
to Firebase Analytics.
property item_id
item_id?: string;
property item_list_id
item_list_id?: string;
property item_list_name
item_list_name?: string;
property items
items?: Item[];
property method
method?: string;
property number
number?: string;
property payment_type
payment_type?: string;
property promotion_id
promotion_id?: string;
property promotion_name
promotion_name?: string;
property promotions
promotions?: Promotion[];
property screen_name
screen_name?: string;
property search_term
search_term?: string;
property shipping
shipping?: Currency;
property shipping_tier
shipping_tier?: string;
property tax
tax?: Currency;
property transaction_id
transaction_id?: string;
property value
value?: number;
interface Item
interface Item {}
property affiliation
affiliation?: string;
property brand
brand?: string;
Deprecated
Use item_brand instead.
property category
category?: string;
Deprecated
Use item_category instead.
property coupon
coupon?: string;
property creative_name
creative_name?: string;
property creative_slot
creative_slot?: string;
property discount
discount?: Currency;
property id
id?: string;
Deprecated
Use item_id instead.
property index
index?: number;
property item_brand
item_brand?: string;
property item_category
item_category?: string;
property item_category2
item_category2?: string;
property item_category3
item_category3?: string;
property item_category4
item_category4?: string;
property item_category5
item_category5?: string;
property item_id
item_id?: string;
property item_list_id
item_list_id?: string;
property item_list_name
item_list_name?: string;
property item_name
item_name?: string;
property item_variant
item_variant?: string;
property location_id
location_id?: string;
property name
name?: string;
Deprecated
Use item_name instead.
property price
price?: Currency;
property promotion_id
promotion_id?: string;
property promotion_name
promotion_name?: string;
property quantity
quantity?: number;
interface Promotion
interface Promotion {}
Deprecated
Use Item instead.
property creative_name
creative_name?: string;
property creative_slot
creative_slot?: string;
property id
id?: string;
property name
name?: string;
interface SettingsOptions
interface SettingsOptions {}
Specifies custom options for your Firebase Analytics instance. You must set these before initializing
firebase.analytics()
.
property dataLayerName
dataLayerName?: string;
Sets custom name for
dataLayer
array used by gtag.
property gtagName
gtagName?: string;
Sets custom name for
gtag
function.
enum EventName
enum EventName { ADD_PAYMENT_INFO = 'add_payment_info', ADD_SHIPPING_INFO = 'add_shipping_info', ADD_TO_CART = 'add_to_cart', ADD_TO_WISHLIST = 'add_to_wishlist', BEGIN_CHECKOUT = 'begin_checkout', CHECKOUT_PROGRESS = 'checkout_progress', EXCEPTION = 'exception', GENERATE_LEAD = 'generate_lead', LOGIN = 'login', PAGE_VIEW = 'page_view', PURCHASE = 'purchase', REFUND = 'refund', REMOVE_FROM_CART = 'remove_from_cart', SCREEN_VIEW = 'screen_view', SEARCH = 'search', SELECT_CONTENT = 'select_content', SELECT_ITEM = 'select_item', SELECT_PROMOTION = 'select_promotion', SET_CHECKOUT_OPTION = 'set_checkout_option', SHARE = 'share', SIGN_UP = 'sign_up', TIMING_COMPLETE = 'timing_complete', VIEW_CART = 'view_cart', VIEW_ITEM = 'view_item', VIEW_ITEM_LIST = 'view_item_list', VIEW_PROMOTION = 'view_promotion', VIEW_SEARCH_RESULTS = 'view_search_results',}
Enum of standard gtag.js event names provided for convenient developer usage.
logEvent
will also accept any custom string and interpret it as a custom event name.
member ADD_PAYMENT_INFO
ADD_PAYMENT_INFO = 'add_payment_info'
member ADD_SHIPPING_INFO
ADD_SHIPPING_INFO = 'add_shipping_info'
member ADD_TO_CART
ADD_TO_CART = 'add_to_cart'
member ADD_TO_WISHLIST
ADD_TO_WISHLIST = 'add_to_wishlist'
member BEGIN_CHECKOUT
BEGIN_CHECKOUT = 'begin_checkout'
member CHECKOUT_PROGRESS
CHECKOUT_PROGRESS = 'checkout_progress'
Deprecated
member EXCEPTION
EXCEPTION = 'exception'
member GENERATE_LEAD
GENERATE_LEAD = 'generate_lead'
member LOGIN
LOGIN = 'login'
member PAGE_VIEW
PAGE_VIEW = 'page_view'
member PURCHASE
PURCHASE = 'purchase'
member REFUND
REFUND = 'refund'
member REMOVE_FROM_CART
REMOVE_FROM_CART = 'remove_from_cart'
member SCREEN_VIEW
SCREEN_VIEW = 'screen_view'
member SEARCH
SEARCH = 'search'
member SELECT_CONTENT
SELECT_CONTENT = 'select_content'
member SELECT_ITEM
SELECT_ITEM = 'select_item'
member SELECT_PROMOTION
SELECT_PROMOTION = 'select_promotion'
member SET_CHECKOUT_OPTION
SET_CHECKOUT_OPTION = 'set_checkout_option'
Deprecated
member SHARE
SHARE = 'share'
member SIGN_UP
SIGN_UP = 'sign_up'
member TIMING_COMPLETE
TIMING_COMPLETE = 'timing_complete'
member VIEW_CART
VIEW_CART = 'view_cart'
member VIEW_ITEM
VIEW_ITEM = 'view_item'
member VIEW_ITEM_LIST
VIEW_ITEM_LIST = 'view_item_list'
member VIEW_PROMOTION
VIEW_PROMOTION = 'view_promotion'
member VIEW_SEARCH_RESULTS
VIEW_SEARCH_RESULTS = 'view_search_results'
type Currency
type Currency = string | number;
type CustomEventName
type CustomEventName<T> = T extends EventNameString ? never : T;
type EventNameString
type EventNameString = | 'add_payment_info' | 'add_shipping_info' | 'add_to_cart' | 'add_to_wishlist' | 'begin_checkout' | 'checkout_progress' | 'exception' | 'generate_lead' | 'login' | 'page_view' | 'purchase' | 'refund' | 'remove_from_cart' | 'screen_view' | 'search' | 'select_content' | 'select_item' | 'select_promotion' | 'set_checkout_option' | 'share' | 'sign_up' | 'timing_complete' | 'view_cart' | 'view_item' | 'view_item_list' | 'view_promotion' | 'view_search_results';
Type for standard gtag.js event names.
logEvent
also accepts any custom string and interprets it as a custom event name.
namespace firebase.app
namespace firebase.app {}
interface App
interface App {}
A Firebase App holds the initialization information for a collection of services.
Do not call this constructor directly. Instead, use `firebase.initializeApp()` to create an app.
property automaticDataCollectionEnabled
automaticDataCollectionEnabled: boolean;
The settable config flag for GDPR opt-in/opt-out
property name
name: string;
The (read-only) name for this app.
The default app's name is
"[DEFAULT]"
.Example 1
// The default app's name is "[DEFAULT]"firebase.initializeApp(defaultAppConfig);console.log(firebase.app().name); // "[DEFAULT]"Example 2
// A named app's name is what you provide to initializeApp()var otherApp = firebase.initializeApp(otherAppConfig, "other");console.log(otherApp.name); // "other"
property options
options: Object;
The (read-only) configuration options for this app. These are the original parameters given in .
Example 1
var app = firebase.initializeApp(config);console.log(app.options.databaseURL === config.databaseURL); // true
method analytics
analytics: () => firebase.analytics.Analytics;
Gets the service for the current app. If the current app is not the default one, throws an error.
The Analytics SDK does not work in a Node.js environment.
Example 1
const analytics = app.analytics();// The above is shorthand for:// const analytics = firebase.analytics(app);
method appCheck
appCheck: () => firebase.appCheck.AppCheck;
method auth
auth: () => firebase.auth.Auth;
Gets the service for the current app.
Example 1
var auth = app.auth();// The above is shorthand for:// var auth = firebase.auth(app);
method database
database: (url?: string) => firebase.database.Database;
Gets the service for the current app.
Example 1
var database = app.database();// The above is shorthand for:// var database = firebase.database(app);
method delete
delete: () => Promise<any>;
Renders this app unusable and frees the resources of all associated services.
Example 1
app.delete().then(function() {console.log("App deleted successfully");}).catch(function(error) {console.log("Error deleting app:", error);});
method firestore
firestore: () => firebase.firestore.Firestore;
method functions
functions: (regionOrCustomDomain?: string) => firebase.functions.Functions;
method installations
installations: () => firebase.installations.Installations;
Gets the service for the current app.
The Installations SDK does not work in a Node.js environment.
Example 1
const installations = app.installations();// The above is shorthand for:// const installations = firebase.installations(app);
method messaging
messaging: () => firebase.messaging.Messaging;
Gets the service for the current app.
The Messaging SDK does not work in a Node.js environment.
Example 1
var messaging = app.messaging();// The above is shorthand for:// var messaging = firebase.messaging(app);
method performance
performance: () => firebase.performance.Performance;
Gets the service for the current app. If the current app is not the default one, throws an error.
The Performance SDK does not work in a Node.js environment.
Example 1
const perf = app.performance();// The above is shorthand for:// const perf = firebase.performance(app);
method remoteConfig
remoteConfig: () => firebase.remoteConfig.RemoteConfig;
Gets the instance.
The Remote Config SDK does not work in a Node.js environment.
Example 1
const rc = app.remoteConfig();// The above is shorthand for:// const rc = firebase.remoteConfig(app);
method storage
storage: (url?: string) => firebase.storage.Storage;
Gets the service for the current app, optionally initialized with a custom storage bucket.
Parameter url
The gs:// url to your Firebase Storage Bucket. If not passed, uses the app's default Storage Bucket.
Example 1
var storage = app.storage();// The above is shorthand for:// var storage = firebase.storage(app);Example 2
var storage = app.storage("gs://your-app.appspot.com");
namespace firebase.appCheck
namespace firebase.appCheck {}
class CustomProvider
class CustomProvider {}
constructor
constructor(options: CustomProviderOptions);
Parameter options
Options for creating the custom provider.
class ReCaptchaEnterpriseProvider
class ReCaptchaEnterpriseProvider {}
constructor
constructor(keyId: string);
Parameter keyId
reCAPTCHA Enterprise key ID.
class ReCaptchaV3Provider
class ReCaptchaV3Provider {}
constructor
constructor(siteKey: string);
Parameter siteKey
reCAPTCHA v3 site key (public key).
interface AppCheck
interface AppCheck {}
The Firebase AppCheck service interface.
Do not call this constructor directly. Instead, use .
method activate
activate: ( provider: | string | ReCaptchaV3Provider | ReCaptchaEnterpriseProvider | CustomProvider | AppCheckProvider | { getToken: () => AppCheckToken }, isTokenAutoRefreshEnabled?: boolean) => void;
Activate AppCheck
Parameter provider
This can be a
ReCaptchaV3Provider
instance, aReCaptchaEnterpriseProvider
instance, aCustomProvider
instance, an object with a customgetToken()
method, or a reCAPTCHA site key.Parameter isTokenAutoRefreshEnabled
If true, the SDK automatically refreshes App Check tokens as needed. If undefined, defaults to the value of
app.automaticDataCollectionEnabled
, which defaults to false and can be set in the app config.
method getToken
getToken: (forceRefresh?: boolean) => Promise<AppCheckTokenResult>;
Get the current App Check token. Attaches to the most recent in-flight request if one is present. Returns null if no token is present and no token requests are in-flight.
Parameter forceRefresh
If true, will always try to fetch a fresh token. If false, will use a cached token if found in storage.
method onTokenChanged
onTokenChanged: { (observer: { next: (tokenResult: AppCheckTokenResult) => void; error?: (error: Error) => void; complete?: () => void; }): Unsubscribe; ( onNext: (tokenResult: AppCheckTokenResult) => void, onError?: (error: Error) => void, onCompletion?: () => void ): Unsubscribe;};
Registers a listener to changes in the token state. There can be more than one listener registered at the same time for one or more App Check instances. The listeners call back on the UI thread whenever the current token associated with this App Check instance changes.
Parameter observer
An object with
next
,error
, andcomplete
properties.next
is called with an whenever the token changes.error
is optional and is called if an error is thrown by the listener (thenext
function).complete
is unused, as the token stream is unending.Returns
A function that unsubscribes this listener.
Registers a listener to changes in the token state. There can be more than one listener registered at the same time for one or more App Check instances. The listeners call back on the UI thread whenever the current token associated with this App Check instance changes.
Parameter onNext
When the token changes, this function is called with aa .
Parameter onError
Optional. Called if there is an error thrown by the listener (the
onNext
function).Parameter onCompletion
Currently unused, as the token stream is unending.
Returns
A function that unsubscribes this listener.
method setTokenAutoRefreshEnabled
setTokenAutoRefreshEnabled: (isTokenAutoRefreshEnabled: boolean) => void;
Parameter isTokenAutoRefreshEnabled
If true, the SDK automatically refreshes App Check tokens as needed. This overrides any value set during
activate()
.
interface AppCheckProvider
interface AppCheckProvider {}
An App Check provider. This can be either the built-in reCAPTCHA provider or a custom provider. For more on custom providers, see https://firebase.google.com/docs/app-check/web-custom-provider
method getToken
getToken: () => Promise<AppCheckToken>;
Returns an AppCheck token.
interface AppCheckToken
interface AppCheckToken {}
The token returned from an .
property expireTimeMillis
readonly expireTimeMillis: number;
The local timestamp after which the token will expire.
property token
readonly token: string;
The token string in JWT format.
interface AppCheckTokenResult
interface AppCheckTokenResult {}
Result returned by .
property token
token: string;
interface CustomProviderOptions
interface CustomProviderOptions {}
Options when creating a CustomProvider.
property getToken
getToken: () => Promise<AppCheckToken>;
Function to get an App Check token through a custom provider service.
namespace firebase.auth
namespace firebase.auth {}
class ActionCodeURL
class ActionCodeURL {}
A utility class to parse email action URLs.
property apiKey
apiKey: string;
The API key of the email action link.
property code
code: string;
The action code of the email action link.
property continueUrl
continueUrl: string;
The continue URL of the email action link. Null if not provided.
property languageCode
languageCode: string;
The language code of the email action link. Null if not provided.
property operation
operation: string;
The action performed by the email action link. It returns from one of the types from firebase.auth.ActionCodeInfo.
property tenantId
tenantId: string;
The tenant ID of the email action link. Null if the email action is from the parent project.
method parseLink
static parseLink: (link: string) => ActionCodeURL;
Parses the email action link string and returns an ActionCodeURL object if the link is valid, otherwise returns null.
Parameter link
The email action link string. The ActionCodeURL object, or null if the link is invalid.
class AuthCredential
abstract class AuthCredential {}
Interface that represents the credentials returned by an auth provider. Implementations specify the details about each auth provider's credential requirements.
property providerId
providerId: string;
The authentication provider ID for the credential. For example, 'facebook.com', or 'google.com'.
property signInMethod
signInMethod: string;
The authentication sign in method for the credential. For example, 'password', or 'emailLink. This corresponds to the sign-in method identifier as returned in firebase.auth.Auth.fetchSignInMethodsForEmail.
method fromJSON
static fromJSON: (json: Object | string) => AuthCredential;
Static method to deserialize a JSON representation of an object into an firebase.auth.AuthCredential. Input can be either Object or the stringified representation of the object. When string is provided, JSON.parse would be called first. If the JSON input does not represent an
AuthCredential
, null is returned.Parameter json
The plain object representation of an AuthCredential.
method toJSON
toJSON: () => Object;
Returns a JSON-serializable representation of this object.
class EmailAuthProvider
class EmailAuthProvider extends EmailAuthProvider_Instance {}
Email and password auth provider implementation.
To authenticate: firebase.auth.Auth.createUserWithEmailAndPassword and firebase.auth.Auth.signInWithEmailAndPassword.
property EMAIL_LINK_SIGN_IN_METHOD
static EMAIL_LINK_SIGN_IN_METHOD: string;
This corresponds to the sign-in method identifier as returned in firebase.auth.Auth.fetchSignInMethodsForEmail.
property EMAIL_PASSWORD_SIGN_IN_METHOD
static EMAIL_PASSWORD_SIGN_IN_METHOD: string;
This corresponds to the sign-in method identifier as returned in firebase.auth.Auth.fetchSignInMethodsForEmail.
property PROVIDER_ID
static PROVIDER_ID: string;
method credential
static credential: (email: string, password: string) => AuthCredential;
Parameter email
Email address.
Parameter password
User account password. The auth provider credential.
Example 1
var cred = firebase.auth.EmailAuthProvider.credential(email,password);
method credentialWithLink
static credentialWithLink: (email: string, emailLink: string) => AuthCredential;
Initialize an
EmailAuthProvider
credential using an email and an email link after a sign in with email link operation.Parameter email
Email address.
Parameter emailLink
Sign-in email link. The auth provider credential.
Example 1
var cred = firebase.auth.EmailAuthProvider.credentialWithLink(email,emailLink);
class EmailAuthProvider_Instance
class EmailAuthProvider_Instance implements firebase.auth.AuthProvider {}
property providerId
providerId: string;
class FacebookAuthProvider
class FacebookAuthProvider extends FacebookAuthProvider_Instance {}
Facebook auth provider.
Example 1
// Sign in using a redirect.firebase.auth().getRedirectResult().then(function(result) {if (result.credential) {// This gives you a Google Access Token.var token = result.credential.accessToken;}var user = result.user;})// Start a sign in process for an unauthenticated user.var provider = new firebase.auth.FacebookAuthProvider();provider.addScope('user_birthday');firebase.auth().signInWithRedirect(provider);Example 2
// Sign in using a popup.var provider = new firebase.auth.FacebookAuthProvider();provider.addScope('user_birthday');firebase.auth().signInWithPopup(provider).then(function(result) {// This gives you a Facebook Access Token.var token = result.credential.accessToken;// The signed-in user info.var user = result.user;});See Also
firebase.auth.Auth.onAuthStateChanged to receive sign in state changes.
property FACEBOOK_SIGN_IN_METHOD
static FACEBOOK_SIGN_IN_METHOD: string;
This corresponds to the sign-in method identifier as returned in firebase.auth.Auth.fetchSignInMethodsForEmail.
property PROVIDER_ID
static PROVIDER_ID: string;
method credential
static credential: (token: string) => OAuthCredential;
Parameter token
Facebook access token.
Example 1
var cred = firebase.auth.FacebookAuthProvider.credential(// `event` from the Facebook auth.authResponseChange callback.event.authResponse.accessToken);
class FacebookAuthProvider_Instance
class FacebookAuthProvider_Instance implements firebase.auth.AuthProvider {}
property providerId
providerId: string;
method addScope
addScope: (scope: string) => AuthProvider;
Parameter scope
Facebook OAuth scope. The provider instance itself.
method setCustomParameters
setCustomParameters: (customOAuthParameters: Object) => AuthProvider;
Sets the OAuth custom parameters to pass in a Facebook OAuth request for popup and redirect sign-in operations. Valid parameters include 'auth_type', 'display' and 'locale'. For a detailed list, check the documentation. Reserved required OAuth 2.0 parameters such as 'client_id', 'redirect_uri', 'scope', 'response_type' and 'state' are not allowed and will be ignored.
Parameter customOAuthParameters
The custom OAuth parameters to pass in the OAuth request. The provider instance itself.
class GithubAuthProvider
class GithubAuthProvider extends GithubAuthProvider_Instance {}
GitHub auth provider.
GitHub requires an OAuth 2.0 redirect, so you can either handle the redirect directly, or use the signInWithPopup handler:
Example 1
// Using a redirect.firebase.auth().getRedirectResult().then(function(result) {if (result.credential) {// This gives you a GitHub Access Token.var token = result.credential.accessToken;}var user = result.user;}).catch(function(error) {// Handle Errors here.var errorCode = error.code;var errorMessage = error.message;// The email of the user's account used.var email = error.email;// The firebase.auth.AuthCredential type that was used.var credential = error.credential;if (errorCode === 'auth/account-exists-with-different-credential') {alert('You have signed up with a different provider for that email.');// Handle linking here if your app allows it.} else {console.error(error);}});// Start a sign in process for an unauthenticated user.var provider = new firebase.auth.GithubAuthProvider();provider.addScope('repo');firebase.auth().signInWithRedirect(provider);Example 2
// With popup.var provider = new firebase.auth.GithubAuthProvider();provider.addScope('repo');firebase.auth().signInWithPopup(provider).then(function(result) {// This gives you a GitHub Access Token.var token = result.credential.accessToken;// The signed-in user info.var user = result.user;}).catch(function(error) {// Handle Errors here.var errorCode = error.code;var errorMessage = error.message;// The email of the user's account used.var email = error.email;// The firebase.auth.AuthCredential type that was used.var credential = error.credential;if (errorCode === 'auth/account-exists-with-different-credential') {alert('You have signed up with a different provider for that email.');// Handle linking here if your app allows it.} else {console.error(error);}});See Also
firebase.auth.Auth.onAuthStateChanged to receive sign in state changes.
property GITHUB_SIGN_IN_METHOD
static GITHUB_SIGN_IN_METHOD: string;
This corresponds to the sign-in method identifier as returned in firebase.auth.Auth.fetchSignInMethodsForEmail.
property PROVIDER_ID
static PROVIDER_ID: string;
method credential
static credential: (token: string) => OAuthCredential;
Parameter token
GitHub access token. {!firebase.auth.OAuthCredential} The auth provider credential.
Example 1
var cred = firebase.auth.GithubAuthProvider.credential(// `event` from the GitHub auth.authResponseChange callback.event.authResponse.accessToken);
class GithubAuthProvider_Instance
class GithubAuthProvider_Instance implements firebase.auth.AuthProvider {}
property providerId
providerId: string;
method addScope
addScope: (scope: string) => AuthProvider;
Parameter scope
GitHub OAuth scope. The provider instance itself.
method setCustomParameters
setCustomParameters: (customOAuthParameters: Object) => AuthProvider;
Sets the OAuth custom parameters to pass in a GitHub OAuth request for popup and redirect sign-in operations. Valid parameters include 'allow_signup'. For a detailed list, check the documentation. Reserved required OAuth 2.0 parameters such as 'client_id', 'redirect_uri', 'scope', 'response_type' and 'state' are not allowed and will be ignored.
Parameter customOAuthParameters
The custom OAuth parameters to pass in the OAuth request. The provider instance itself.
class GoogleAuthProvider
class GoogleAuthProvider extends GoogleAuthProvider_Instance {}
Google auth provider.
Example 1
// Using a redirect.firebase.auth().getRedirectResult().then(function(result) {if (result.credential) {// This gives you a Google Access Token.var token = result.credential.accessToken;}var user = result.user;});// Start a sign in process for an unauthenticated user.var provider = new firebase.auth.GoogleAuthProvider();provider.addScope('profile');provider.addScope('email');firebase.auth().signInWithRedirect(provider);Example 2
// Using a popup.var provider = new firebase.auth.GoogleAuthProvider();provider.addScope('profile');provider.addScope('email');firebase.auth().signInWithPopup(provider).then(function(result) {// This gives you a Google Access Token.var token = result.credential.accessToken;// The signed-in user info.var user = result.user;});See Also
firebase.auth.Auth.onAuthStateChanged to receive sign in state changes.
property GOOGLE_SIGN_IN_METHOD
static GOOGLE_SIGN_IN_METHOD: string;
This corresponds to the sign-in method identifier as returned in firebase.auth.Auth.fetchSignInMethodsForEmail.
property PROVIDER_ID
static PROVIDER_ID: string;
method credential
static credential: ( idToken?: string | null, accessToken?: string | null) => OAuthCredential;
Creates a credential for Google. At least one of ID token and access token is required.
Parameter idToken
Google ID token.
Parameter accessToken
Google access token. The auth provider credential.
Example 1
// \`googleUser\` from the onsuccess Google Sign In callback.var credential = firebase.auth.GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token);firebase.auth().signInWithCredential(credential)
class GoogleAuthProvider_Instance
class GoogleAuthProvider_Instance implements firebase.auth.AuthProvider {}
property providerId
providerId: string;
method addScope
addScope: (scope: string) => AuthProvider;
Parameter scope
Google OAuth scope. The provider instance itself.
method setCustomParameters
setCustomParameters: (customOAuthParameters: Object) => AuthProvider;
Sets the OAuth custom parameters to pass in a Google OAuth request for popup and redirect sign-in operations. Valid parameters include 'hd', 'hl', 'include_granted_scopes', 'login_hint' and 'prompt'. For a detailed list, check the documentation. Reserved required OAuth 2.0 parameters such as 'client_id', 'redirect_uri', 'scope', 'response_type' and 'state' are not allowed and will be ignored.
Parameter customOAuthParameters
The custom OAuth parameters to pass in the OAuth request. The provider instance itself.
class MultiFactorAssertion
abstract class MultiFactorAssertion {}
The base class for asserting ownership of a second factor. This is used to facilitate enrollment of a second factor on an existing user or sign-in of a user who already verified the first factor.
property factorId
factorId: string;
The identifier of the second factor.
class MultiFactorResolver
class MultiFactorResolver {}
The class used to facilitate recovery from firebase.auth.MultiFactorError when a user needs to provide a second factor to sign in.
Example 1
firebase.auth().signInWithEmailAndPassword().then(function(result) {// User signed in. No 2nd factor challenge is needed.}).catch(function(error) {if (error.code == 'auth/multi-factor-auth-required') {var resolver = error.resolver;// Show UI to let user select second factor.var multiFactorHints = resolver.hints;} else {// Handle other errors.}});// The enrolled second factors that can be used to complete// sign-in are returned in the `MultiFactorResolver.hints` list.// UI needs to be presented to allow the user to select a second factor// from that list.var selectedHint = // ; selected from multiFactorHintsvar phoneAuthProvider = new firebase.auth.PhoneAuthProvider();var phoneInfoOptions = {multiFactorHint: selectedHint,session: resolver.session};phoneAuthProvider.verifyPhoneNumber(phoneInfoOptions,appVerifier).then(function(verificationId) {// store verificationID and show UI to let user enter verification code.});// UI to enter verification code and continue.// Continue button click handlervar phoneAuthCredential =firebase.auth.PhoneAuthProvider.credential(verificationId, verificationCode);var multiFactorAssertion =firebase.auth.PhoneMultiFactorGenerator.assertion(phoneAuthCredential);resolver.resolveSignIn(multiFactorAssertion).then(function(userCredential) {// User signed in.});
property auth
auth: Auth;
The Auth instance used to sign in with the first factor.
property hints
hints: MultiFactorInfo[];
The list of hints for the second factors needed to complete the sign-in for the current session.
property session
session: MultiFactorSession;
The session identifier for the current sign-in flow, which can be used to complete the second factor sign-in.
method resolveSignIn
resolveSignIn: (assertion: MultiFactorAssertion) => Promise<UserCredential>;
A helper function to help users complete sign in with a second factor using an firebase.auth.MultiFactorAssertion confirming the user successfully completed the second factor challenge.
Error Codes auth/invalid-verification-code Thrown if the verification code is not valid. auth/missing-verification-code Thrown if the verification code is missing. auth/invalid-verification-id Thrown if the credential is a firebase.auth.PhoneAuthProvider.credential and the verification ID of the credential is not valid. auth/missing-verification-id Thrown if the verification ID is missing. auth/code-expired Thrown if the verification code has expired. auth/invalid-multi-factor-session Thrown if the request does not contain a valid proof of first factor successful sign-in. auth/missing-multi-factor-session Thrown if The request is missing proof of first factor successful sign-in.
Parameter assertion
The multi-factor assertion to resolve sign-in with. The promise that resolves with the user credential object.
class MultiFactorSession
class MultiFactorSession {}
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.
class OAuthCredential
class OAuthCredential extends AuthCredential {}
Interface that represents the OAuth credentials returned by an OAuth provider. Implementations specify the details about each auth provider's credential requirements.
property accessToken
accessToken?: string;
The OAuth access token associated with the credential if it belongs to an OAuth provider, such as
facebook.com
,twitter.com
, etc.
property idToken
idToken?: string;
The OAuth ID token associated with the credential if it belongs to an OIDC provider, such as
google.com
.
property secret
secret?: string;
The OAuth access token secret associated with the credential if it belongs to an OAuth 1.0 provider, such as
twitter.com
.
class OAuthProvider
class OAuthProvider implements firebase.auth.AuthProvider {}
Generic OAuth provider.
Parameter providerId
The associated provider ID, such as
github.com
.Example 1
// Using a redirect.firebase.auth().getRedirectResult().then(function(result) {if (result.credential) {// This gives you the OAuth Access Token for that provider.var token = result.credential.accessToken;}var user = result.user;});// Start a sign in process for an unauthenticated user.var provider = new firebase.auth.OAuthProvider('google.com');provider.addScope('profile');provider.addScope('email');firebase.auth().signInWithRedirect(provider);Example 2
// Using a popup.var provider = new firebase.auth.OAuthProvider('google.com');provider.addScope('profile');provider.addScope('email');firebase.auth().signInWithPopup(provider).then(function(result) {// This gives you the OAuth Access Token for that provider.var token = result.credential.accessToken;// The signed-in user info.var user = result.user;});See Also
firebase.auth.Auth.onAuthStateChanged to receive sign in state changes.
constructor
constructor(providerId: string);
property providerId
providerId: string;
method addScope
addScope: (scope: string) => AuthProvider;
Parameter scope
Provider OAuth scope to add.
method credential
credential: ( optionsOrIdToken: string | OAuthCredentialOptions, accessToken?: string) => OAuthCredential;
Creates a Firebase credential from a generic OAuth provider's access token or ID token. The raw nonce is required when an ID token with a nonce field is provided. The SHA-256 hash of the raw nonce must match the nonce field in the ID token.
Parameter optionsOrIdToken
Either the options object containing the ID token, access token and raw nonce or the ID token string.
Parameter accessToken
The OAuth access token.
Example 1
// `googleUser` from the onsuccess Google Sign In callback.// Initialize a generate OAuth provider with a `google.com` providerId.var provider = new firebase.auth.OAuthProvider('google.com');var credential = provider.credential({idToken: googleUser.getAuthResponse().id_token,});firebase.auth().signInWithCredential(credential)
method setCustomParameters
setCustomParameters: (customOAuthParameters: Object) => AuthProvider;
Sets the OAuth custom parameters to pass in an OAuth request for popup and redirect sign-in operations. For a detailed list, check the reserved required OAuth 2.0 parameters such as
client_id
,redirect_uri
,scope
,response_type
andstate
are not allowed and will be ignored.Parameter customOAuthParameters
The custom OAuth parameters to pass in the OAuth request.
class PhoneAuthCredential
class PhoneAuthCredential extends AuthCredential {}
Classes that represents the Phone Auth credentials returned by a firebase.auth.PhoneAuthProvider.
class PhoneAuthProvider
class PhoneAuthProvider extends PhoneAuthProvider_Instance {}
Phone number auth provider.
Parameter auth
The Firebase Auth instance in which sign-ins should occur. Uses the default Auth instance if unspecified.
Example 1
// 'recaptcha-container' is the ID of an element in the DOM.var applicationVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');var provider = new firebase.auth.PhoneAuthProvider();provider.verifyPhoneNumber('+16505550101', applicationVerifier).then(function(verificationId) {var verificationCode = window.prompt('Please enter the verification ' +'code that was sent to your mobile device.');return firebase.auth.PhoneAuthProvider.credential(verificationId,verificationCode);}).then(function(phoneCredential) {return firebase.auth().signInWithCredential(phoneCredential);});
property PHONE_SIGN_IN_METHOD
static PHONE_SIGN_IN_METHOD: string;
This corresponds to the sign-in method identifier as returned in firebase.auth.Auth.fetchSignInMethodsForEmail.
property PROVIDER_ID
static PROVIDER_ID: string;
method credential
static credential: ( verificationId: string, verificationCode: string) => AuthCredential;
Creates a phone auth credential, given the verification ID from firebase.auth.PhoneAuthProvider.verifyPhoneNumber and the code that was sent to the user's mobile device.
Error Codes auth/missing-verification-code Thrown if the verification code is missing. auth/missing-verification-id Thrown if the verification ID is missing.
Parameter verificationId
The verification ID returned from firebase.auth.PhoneAuthProvider.verifyPhoneNumber.
Parameter verificationCode
The verification code sent to the user's mobile device. The auth provider credential.
class PhoneAuthProvider_Instance
class PhoneAuthProvider_Instance implements firebase.auth.AuthProvider {}
constructor
constructor(auth?: Auth);
property providerId
providerId: string;
method verifyPhoneNumber
verifyPhoneNumber: ( phoneInfoOptions: string | PhoneInfoOptions, applicationVerifier: ApplicationVerifier) => Promise<string>;
Starts a phone number authentication flow by sending a verification code to the given phone number. Returns an ID that can be passed to firebase.auth.PhoneAuthProvider.credential to identify this flow.
For abuse prevention, this method also requires a firebase.auth.ApplicationVerifier. The Firebase Auth SDK includes a reCAPTCHA-based implementation, firebase.auth.RecaptchaVerifier.
Error Codes auth/captcha-check-failed Thrown if the reCAPTCHA response token was invalid, expired, or if this method was called from a non-whitelisted domain. auth/invalid-phone-number Thrown if the phone number has an invalid format. auth/missing-phone-number Thrown if the phone number is missing. auth/quota-exceeded Thrown if the SMS quota for the Firebase project has been exceeded. auth/user-disabled Thrown if the user corresponding to the given phone number has been disabled. auth/maximum-second-factor-count-exceeded Thrown if The maximum allowed number of second factors on a user has been exceeded. auth/second-factor-already-in-use Thrown if the second factor is already enrolled on this account. auth/unsupported-first-factor Thrown if the first factor being used to sign in is not supported. auth/unverified-email Thrown if the email of the account is not verified.
Parameter phoneInfoOptions
The user's firebase.auth.PhoneInfoOptions. The phone number should be in E.164 format (e.g. +16505550101).
Parameter applicationVerifier
A Promise for the verification ID.
class PhoneMultiFactorAssertion
class PhoneMultiFactorAssertion extends firebase.auth.MultiFactorAssertion {}
The class for asserting ownership of a phone second factor.
class PhoneMultiFactorGenerator
class PhoneMultiFactorGenerator {}
The class used to initialize firebase.auth.PhoneMultiFactorAssertion.
property FACTOR_ID
static FACTOR_ID: string;
The identifier of the phone second factor:
phone
.
method assertion
static assertion: ( phoneAuthCredential: PhoneAuthCredential) => PhoneMultiFactorAssertion;
Initializes the firebase.auth.PhoneMultiFactorAssertion to confirm ownership of the phone second factor.
class RecaptchaVerifier
class RecaptchaVerifier extends RecaptchaVerifier_Instance {}
An -based application verifier.
This class does not work in a Node.js environment.
Parameter container
The reCAPTCHA container parameter. This has different meaning depending on whether the reCAPTCHA is hidden or visible. For a visible reCAPTCHA the container must be empty. If a string is used, it has to correspond to an element ID. The corresponding element must also must be in the DOM at the time of initialization.
Parameter parameters
The optional reCAPTCHA parameters. Check the reCAPTCHA docs for a comprehensive list. All parameters are accepted except for the sitekey. Firebase Auth backend provisions a reCAPTCHA for each project and will configure this upon rendering. For an invisible reCAPTCHA, a size key must have the value 'invisible'.
Parameter app
The corresponding Firebase app. If none is provided, the default Firebase App instance is used. A Firebase App instance must be initialized with an API key, otherwise an error will be thrown.
class RecaptchaVerifier_Instance
class RecaptchaVerifier_Instance implements firebase.auth.ApplicationVerifier {}
constructor
constructor(container: any, parameters?: Object, app?: app.App);
property type
type: string;
The application verifier type. For a reCAPTCHA verifier, this is 'recaptcha'.
method clear
clear: () => void;
Clears the reCAPTCHA widget from the page and destroys the current instance.
method render
render: () => Promise<number>;
Renders the reCAPTCHA widget on the page. A Promise that resolves with the reCAPTCHA widget ID.
method verify
verify: () => Promise<string>;
Waits for the user to solve the reCAPTCHA and resolves with the reCAPTCHA token. A Promise for the reCAPTCHA token.
class SAMLAuthProvider
class SAMLAuthProvider implements firebase.auth.AuthProvider {}
constructor
constructor(providerId: string);
property providerId
providerId: string;
class TwitterAuthProvider
class TwitterAuthProvider extends TwitterAuthProvider_Instance {}
Twitter auth provider.
Example 1
// Using a redirect.firebase.auth().getRedirectResult().then(function(result) {if (result.credential) {// For accessing the Twitter API.var token = result.credential.accessToken;var secret = result.credential.secret;}var user = result.user;});// Start a sign in process for an unauthenticated user.var provider = new firebase.auth.TwitterAuthProvider();firebase.auth().signInWithRedirect(provider);Example 2
// Using a popup.var provider = new firebase.auth.TwitterAuthProvider();firebase.auth().signInWithPopup(provider).then(function(result) {// For accessing the Twitter API.var token = result.credential.accessToken;var secret = result.credential.secret;// The signed-in user info.var user = result.user;});See Also
firebase.auth.Auth.onAuthStateChanged to receive sign in state changes.
property PROVIDER_ID
static PROVIDER_ID: string;
property TWITTER_SIGN_IN_METHOD
static TWITTER_SIGN_IN_METHOD: string;
This corresponds to the sign-in method identifier as returned in firebase.auth.Auth.fetchSignInMethodsForEmail.
method credential
static credential: (token: string, secret: string) => OAuthCredential;
Parameter token
Twitter access token.
Parameter secret
Twitter secret. The auth provider credential.
class TwitterAuthProvider_Instance
class TwitterAuthProvider_Instance implements firebase.auth.AuthProvider {}
property providerId
providerId: string;
method setCustomParameters
setCustomParameters: (customOAuthParameters: Object) => AuthProvider;
Sets the OAuth custom parameters to pass in a Twitter OAuth request for popup and redirect sign-in operations. Valid parameters include 'lang'. Reserved required OAuth 1.0 parameters such as 'oauth_consumer_key', 'oauth_token', 'oauth_signature', etc are not allowed and will be ignored.
Parameter customOAuthParameters
The custom OAuth parameters to pass in the OAuth request. The provider instance itself.
interface ActionCodeInfo
interface ActionCodeInfo {}
A response from firebase.auth.Auth.checkActionCode.
property data
data: { email?: string | null; /** * @deprecated * This field is deprecated in favor of previousEmail. */ fromEmail?: string | null; multiFactorInfo?: firebase.auth.MultiFactorInfo | null; previousEmail?: string | null;};
The data associated with the action code.
For the
PASSWORD_RESET
,VERIFY_EMAIL
, andRECOVER_EMAIL
actions, this object contains anemail
field with the address the email was sent to.For the RECOVER_EMAIL action, which allows a user to undo an email address change, this object also contains a
previousEmail
field with the user account's current email address. After the action completes, the user's email address will revert to the value in theemail
field from the value inpreviousEmail
field.For the VERIFY_AND_CHANGE_EMAIL action, which allows a user to verify the email before updating it, this object contains a
previousEmail
field with the user account's email address before updating. After the action completes, the user's email address will be updated to the value in theemail
field from the value inpreviousEmail
field.For the REVERT_SECOND_FACTOR_ADDITION action, which allows a user to unenroll a newly added second factor, this object contains a
multiFactorInfo
field with the information about the second factor. For phone second factor, themultiFactorInfo
is a firebase.auth.PhoneMultiFactorInfo object, which contains the phone number.
property operation
operation: string;
The type of operation that generated the action code. This could be:
EMAIL_SIGNIN
: email sign in code generated via firebase.auth.Auth.sendSignInLinkToEmail.PASSWORD_RESET
: password reset code generated via firebase.auth.Auth.sendPasswordResetEmail.RECOVER_EMAIL
: email change revocation code generated via firebase.User.updateEmail.REVERT_SECOND_FACTOR_ADDITION
: revert second factor addition code generated via firebase.User.MultiFactorUser.enroll.VERIFY_AND_CHANGE_EMAIL
: verify and change email code generated via firebase.User.verifyBeforeUpdateEmail.VERIFY_EMAIL
: email verification code generated via firebase.User.sendEmailVerification.
interface ApplicationVerifier
interface ApplicationVerifier {}
A verifier for domain verification and abuse prevention. Currently, the only implementation is firebase.auth.RecaptchaVerifier.
interface Auth
interface Auth {}
The Firebase Auth service interface.
Do not call this constructor directly. Instead, use .
See for a full guide on how to use the Firebase Auth service.
property app
app: firebase.app.App;
The associated with the
Auth
service instance.Example 1
var app = auth.app;
property config
readonly config: Config;
The config used to initialize this instance.
property currentUser
currentUser: firebase.User | null;
The currently signed-in user (or null).
property emulatorConfig
readonly emulatorConfig: EmulatorConfig | null;
The current emulator configuration (or null).
property languageCode
languageCode: string | null;
The current Auth instance's language code. This is a readable/writable property. When set to null, the default Firebase Console language setting is applied. The language code will propagate to email action templates (password reset, email verification and email change revocation), SMS templates for phone authentication, reCAPTCHA verifier and OAuth popup/redirect operations provided the specified providers support localization with the language code specified.
property name
readonly name: string;
The name of the app associated with the Auth service instance.
property settings
settings: firebase.auth.AuthSettings;
The current Auth instance's settings. This is used to edit/read configuration related options like app verification mode for phone authentication.
property tenantId
tenantId: string | null;
The current Auth instance's tenant ID. This is a readable/writable property. When you set the tenant ID of an Auth instance, all future sign-in/sign-up operations will pass this tenant ID and sign in or sign up users to the specified tenant project. When set to null, users are signed in to the parent project. By default, this is set to null.
Example 1
// Set the tenant ID on Auth instance.firebase.auth().tenantId = ‘TENANT_PROJECT_ID’;// All future sign-in request now include tenant ID.firebase.auth().signInWithEmailAndPassword(email, password).then(function(result) {// result.user.tenantId should be ‘TENANT_PROJECT_ID’.}).catch(function(error) {// Handle error.});
method applyActionCode
applyActionCode: (code: string) => Promise<void>;
Applies a verification code sent to the user by email or other out-of-band mechanism.
Error Codes auth/expired-action-code Thrown if the action code has expired. auth/invalid-action-code Thrown if the action code is invalid. This can happen if the code is malformed or has already been used. auth/user-disabled Thrown if the user corresponding to the given action code has been disabled. auth/user-not-found Thrown if there is no user corresponding to the action code. This may have happened if the user was deleted between when the action code was issued and when this method was called.
Parameter code
A verification code sent to the user.
method checkActionCode
checkActionCode: (code: string) => Promise<ActionCodeInfo>;
Checks a verification code sent to the user by email or other out-of-band mechanism.
Returns metadata about the code.
Error Codes auth/expired-action-code Thrown if the action code has expired. auth/invalid-action-code Thrown if the action code is invalid. This can happen if the code is malformed or has already been used. auth/user-disabled Thrown if the user corresponding to the given action code has been disabled. auth/user-not-found Thrown if there is no user corresponding to the action code. This may have happened if the user was deleted between when the action code was issued and when this method was called.
Parameter code
A verification code sent to the user.
method confirmPasswordReset
confirmPasswordReset: (code: string, newPassword: string) => Promise<void>;
Completes the password reset process, given a confirmation code and new password.
Error Codes auth/expired-action-code Thrown if the password reset code has expired. auth/invalid-action-code Thrown if the password reset code is invalid. This can happen if the code is malformed or has already been used. auth/user-disabled Thrown if the user corresponding to the given password reset code has been disabled. auth/user-not-found Thrown if there is no user corresponding to the password reset code. This may have happened if the user was deleted between when the code was issued and when this method was called. auth/weak-password Thrown if the new password is not strong enough.
Parameter code
The confirmation code send via email to the user.
Parameter newPassword
The new password.
method createUserWithEmailAndPassword
createUserWithEmailAndPassword: ( email: string, password: string) => Promise<UserCredential>;
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.
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.
Error Codes auth/email-already-in-use Thrown if there already exists an account with the given email address. auth/invalid-email Thrown if the email address is not valid. auth/operation-not-allowed Thrown if email/password accounts are not enabled. Enable email/password accounts in the Firebase Console, under the Auth tab. auth/weak-password Thrown if the password is not strong enough.
Parameter email
The user's email address.
Parameter password
The user's chosen password.
Example 1
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {// Handle Errors here.var errorCode = error.code;var errorMessage = error.message;if (errorCode == 'auth/weak-password') {alert('The password is too weak.');} else {alert(errorMessage);}console.log(error);});
method fetchSignInMethodsForEmail
fetchSignInMethodsForEmail: (email: string) => Promise<Array<string>>;
Gets the list of possible sign in methods for the given email address. This is useful to differentiate methods of sign-in for the same provider, eg.
EmailAuthProvider
which has 2 methods of sign-in, email/password and email/link.Error Codes auth/invalid-email Thrown if the email address is not valid.
method getRedirectResult
getRedirectResult: () => Promise<UserCredential>;
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
.Error Codes auth/account-exists-with-different-credential Thrown if there already exists an account with the email address asserted by the credential. Resolve this by calling firebase.auth.Auth.fetchSignInMethodsForEmail with the error.email and then asking the user to sign in using one of the returned providers. Once the user is signed in, the original credential retrieved from the error.credential can be linked to the user with firebase.User.linkWithCredential to prevent the user from signing in again to the original provider via popup or redirect. If you are using redirects for sign in, save the credential in session storage and then retrieve on redirect and repopulate the credential using for example firebase.auth.GoogleAuthProvider.credential depending on the credential provider id and complete the link. auth/auth-domain-config-required Thrown if authDomain configuration is not provided when calling firebase.initializeApp(). Check Firebase Console for instructions on determining and passing that field. auth/credential-already-in-use Thrown if the account corresponding to the credential already exists among your users, or is already linked to a Firebase User. For example, this error could be thrown if you are upgrading an anonymous user to a Google user by linking a Google credential to it and the Google credential used is already associated with an existing Firebase Google user. An error.email and error.credential (firebase.auth.AuthCredential) fields are also provided. You can recover from this error by signing in with that credential directly via firebase.auth.Auth.signInWithCredential. auth/email-already-in-use Thrown if the email corresponding to the credential already exists among your users. When thrown while linking a credential to an existing user, an error.email and error.credential (firebase.auth.AuthCredential) fields are also provided. You have to link the credential to the existing user with that email if you wish to continue signing in with that credential. To do so, call firebase.auth.Auth.fetchSignInMethodsForEmail, sign in to error.email via one of the providers returned and then firebase.User.linkWithCredential the original credential to that newly signed in user. auth/operation-not-allowed Thrown if the type of account corresponding to the credential is not enabled. Enable the account type in the Firebase Console, under the Auth tab. auth/operation-not-supported-in-this-environment Thrown if this operation is not supported in the environment your application is running on. "location.protocol" must be http or https. auth/timeout Thrown typically if the app domain is not authorized for OAuth operations for your Firebase project. Edit the list of authorized domains from the Firebase console.
This method does not work in a Node.js environment.
Example 1
// First, we perform the signInWithRedirect.// Creates the provider object.var provider = new firebase.auth.FacebookAuthProvider();// You can add additional scopes to the provider:provider.addScope('email');provider.addScope('user_friends');// Sign in with redirect:auth.signInWithRedirect(provider)////////////////////////////////////////////////////////////// The user is redirected to the provider's sign in flow...////////////////////////////////////////////////////////////// Then redirected back to the app, where we check the redirect result:auth.getRedirectResult().then(function(result) {// The firebase.User instance:var user = result.user;// The Facebook firebase.auth.AuthCredential containing the Facebook// access token:var credential = result.credential;// As this API can be used for sign-in, linking and reauthentication,// check the operationType to determine what triggered this redirect// operation.var operationType = result.operationType;}, function(error) {// The provider's account email, can be used in case of// auth/account-exists-with-different-credential to fetch the providers// linked to the email:var email = error.email;// The provider's credential:var credential = error.credential;// In case of auth/account-exists-with-different-credential error,// you can fetch the providers using this:if (error.code === 'auth/account-exists-with-different-credential') {auth.fetchSignInMethodsForEmail(email).then(function(providers) {// The returned 'providers' is a list of the available providers// linked to the email address. Please refer to the guide for a more// complete explanation on how to recover from this error.});}});
method isSignInWithEmailLink
isSignInWithEmailLink: (emailLink: string) => boolean;
Checks if an incoming link is a sign-in with email link.
method onAuthStateChanged
onAuthStateChanged: ( nextOrObserver: | Observer<any, globalThis.Error> | ((a: firebase.User | null) => any), error?: (a: Error) => any, completed?: firebase.Unsubscribe) => firebase.Unsubscribe;
Adds an observer for changes to the user's sign-in state.
Prior to 4.0.0, this triggered the observer when users were signed in, signed out, or when the user's ID token changed in situations such as token expiry or password change. After 4.0.0, the observer is only triggered on sign-in or sign-out.
To keep the old behavior, see firebase.auth.Auth.onIdTokenChanged.
Example 1
firebase.auth().onAuthStateChanged(function(user) {if (user) {// User is signed in.}});
method onIdTokenChanged
onIdTokenChanged: ( nextOrObserver: | Observer<any, globalThis.Error> | ((a: firebase.User | null) => any), error?: (a: Error) => any, completed?: firebase.Unsubscribe) => firebase.Unsubscribe;
Adds an observer for changes to the signed-in user's ID token, which includes sign-in, sign-out, and token refresh events. This method has the same behavior as firebase.auth.Auth.onAuthStateChanged had prior to 4.0.0.
Parameter nextOrObserver
An observer object or a function triggered on change.
Parameter error
Optional A function triggered on auth error.
Parameter completed
Optional A function triggered when the observer is removed.
Example 1
firebase.auth().onIdTokenChanged(function(user) {if (user) {// User is signed in or token was refreshed.}});
method sendPasswordResetEmail
sendPasswordResetEmail: ( email: string, actionCodeSettings?: ActionCodeSettings) => Promise<void>;
Sends a password reset email to the given email address.
To complete the password reset, call firebase.auth.Auth.confirmPasswordReset with the code supplied in the email sent to the user, along with the new password specified by the user.
Error Codes auth/invalid-email Thrown if the email address is not valid. auth/missing-android-pkg-name An Android package name must be provided if the Android app is required to be installed. auth/missing-continue-uri A continue URL must be provided in the request. auth/missing-ios-bundle-id An iOS Bundle ID must be provided if an App Store ID is provided. auth/invalid-continue-uri The continue URL provided in the request is invalid. auth/unauthorized-continue-uri The domain of the continue URL is not whitelisted. Whitelist the domain in the Firebase console. auth/user-not-found Thrown if there is no user corresponding to the email address.
Parameter email
The email address with the password to be reset.
Parameter actionCodeSettings
The action code settings. If specified, the state/continue URL will be set as the "continueUrl" parameter in the password reset link. The default password reset landing page will use this to display a link to go back to the app if it is installed. If the actionCodeSettings is not specified, no URL is appended to the action URL. The state URL provided must belong to a domain that is whitelisted by the developer in the console. Otherwise an error will be thrown. Mobile app redirects will only be applicable if the developer configures and accepts the Firebase Dynamic Links terms of condition. The Android package name and iOS bundle ID will be respected only if they are configured in the same Firebase Auth project used.
Example 1
var actionCodeSettings = {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};firebase.auth().sendPasswordResetEmail('user@example.com', actionCodeSettings).then(function() {// Password reset email sent.}).catch(function(error) {// Error occurred. Inspect error.code.});
method sendSignInLinkToEmail
sendSignInLinkToEmail: ( email: string, actionCodeSettings: ActionCodeSettings) => Promise<void>;
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 firebase.auth.Auth.signInWithEmailLink with the email address and the email link supplied in the email sent to the user.
Error Codes auth/argument-error Thrown if handleCodeInApp is false. auth/invalid-email Thrown if the email address is not valid. auth/missing-android-pkg-name An Android package name must be provided if the Android app is required to be installed. auth/missing-continue-uri A continue URL must be provided in the request. auth/missing-ios-bundle-id An iOS Bundle ID must be provided if an App Store ID is provided. auth/invalid-continue-uri The continue URL provided in the request is invalid. auth/unauthorized-continue-uri The domain of the continue URL is not whitelisted. Whitelist the domain in the Firebase console.
Parameter email
The email account to sign in with.
Parameter actionCodeSettings
The action code settings. The action code settings which provides Firebase with instructions on how to construct the email link. This includes the sign in completion URL or the deep link for mobile redirects, the mobile apps to use when the sign-in link is opened on an Android or iOS device. Mobile app redirects will only be applicable if the developer configures and accepts the Firebase Dynamic Links terms of condition. The Android package name and iOS bundle ID will be respected only if they are configured in the same Firebase Auth project used.
Example 1
var actionCodeSettings = {// The URL to redirect to for sign-in completion. This is also the deep// link for mobile redirects. The domain (www.example.com) for this URL// must be whitelisted in the Firebase Console.url: 'https://www.example.com/finishSignUp?cartId=1234',iOS: {bundleId: 'com.example.ios'},android: {packageName: 'com.example.android',installApp: true,minimumVersion: '12'},// This must be true.handleCodeInApp: true};firebase.auth().sendSignInLinkToEmail('user@example.com', actionCodeSettings).then(function() {// The link was successfully sent. Inform the user. Save the email// locally so you don't need to ask the user for it again if they open// the link on the same device.}).catch(function(error) {// Some error occurred, you can inspect the code: error.code});
method setPersistence
setPersistence: (persistence: string) => Promise<void>;
Changes the current type of persistence on the current 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 will return a promise that will resolve once the state finishes copying from one type of storage to the other. Calling a sign-in method after changing persistence will wait for that persistence change to complete before applying it on the new Auth state.
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.
The default for web browser apps and React Native apps is 'local' (provided the browser supports this mechanism) whereas it is 'none' for Node.js backend apps.
Error Codes (thrown synchronously) auth/invalid-persistence-type Thrown if the specified persistence type is invalid. auth/unsupported-persistence-type Thrown if the current environment does not support the specified persistence type.
Example 1
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION).then(function() {// Existing and future Auth states are now persisted in the current// session only. Closing the window would clear any existing state even if// a user forgets to sign out.});
method signInAndRetrieveDataWithCredential
signInAndRetrieveDataWithCredential: ( credential: AuthCredential) => Promise<UserCredential>;
Asynchronously signs in with the given credentials, and returns any available additional user information, such as user name.
Error Codes auth/account-exists-with-different-credential Thrown if there already exists an account with the email address asserted by the credential. Resolve this by calling firebase.auth.Auth.fetchSignInMethodsForEmail and then asking the user to sign in using one of the returned providers. Once the user is signed in, the original credential can be linked to the user with firebase.User.linkWithCredential. auth/invalid-credential Thrown if the credential is malformed or has expired. auth/operation-not-allowed Thrown if the type of account corresponding to the credential is not enabled. Enable the account type in the Firebase Console, under the Auth tab. auth/user-disabled Thrown if the user corresponding to the given credential has been disabled. auth/user-not-found Thrown if signing in with a credential from firebase.auth.EmailAuthProvider.credential and there is no user corresponding to the given email. auth/wrong-password Thrown if signing in with a credential from firebase.auth.EmailAuthProvider.credential and the password is invalid for the given email, or if the account corresponding to the email does not have a password set. auth/invalid-verification-code Thrown if the credential is a firebase.auth.PhoneAuthProvider.credential and the verification code of the credential is not valid. auth/invalid-verification-id Thrown if the credential is a firebase.auth.PhoneAuthProvider.credential and the verification ID of the credential is not valid.
Parameter credential
The auth credential.
Example 1
firebase.auth().signInAndRetrieveDataWithCredential(credential).then(function(userCredential) {console.log(userCredential.additionalUserInfo.username);});Deprecated
This method is deprecated. Use firebase.auth.Auth.signInWithCredential instead.
method signInAnonymously
signInAnonymously: () => Promise<UserCredential>;
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.
Error Codes auth/operation-not-allowed Thrown if anonymous accounts are not enabled. Enable anonymous accounts in the Firebase Console, under the Auth tab.
Example 1
firebase.auth().signInAnonymously().catch(function(error) {// Handle Errors here.var errorCode = error.code;var errorMessage = error.message;if (errorCode === 'auth/operation-not-allowed') {alert('You must enable Anonymous auth in the Firebase Console.');} else {console.error(error);}});
method signInWithCredential
signInWithCredential: (credential: AuthCredential) => Promise<UserCredential>;
Asynchronously signs in with the given credentials.
Error Codes auth/account-exists-with-different-credential Thrown if there already exists an account with the email address asserted by the credential. Resolve this by calling firebase.auth.Auth.fetchSignInMethodsForEmail and then asking the user to sign in using one of the returned providers. Once the user is signed in, the original credential can be linked to the user with firebase.User.linkWithCredential. auth/invalid-credential Thrown if the credential is malformed or has expired. auth/operation-not-allowed Thrown if the type of account corresponding to the credential is not enabled. Enable the account type in the Firebase Console, under the Auth tab. auth/user-disabled Thrown if the user corresponding to the given credential has been disabled. auth/user-not-found Thrown if signing in with a credential from firebase.auth.EmailAuthProvider.credential and there is no user corresponding to the given email. auth/wrong-password Thrown if signing in with a credential from firebase.auth.EmailAuthProvider.credential and the password is invalid for the given email, or if the account corresponding to the email does not have a password set. auth/invalid-verification-code Thrown if the credential is a firebase.auth.PhoneAuthProvider.credential and the verification code of the credential is not valid. auth/invalid-verification-id Thrown if the credential is a firebase.auth.PhoneAuthProvider.credential and the verification ID of the credential is not valid.
Parameter credential
The auth credential.
Example 1
firebase.auth().signInWithCredential(credential).catch(function(error) {// Handle Errors here.var errorCode = error.code;var errorMessage = error.message;// The email of the user's account used.var email = error.email;// The firebase.auth.AuthCredential type that was used.var credential = error.credential;if (errorCode === 'auth/account-exists-with-different-credential') {alert('Email already associated with another account.');// Handle account linking here, if using.} else {console.error(error);}});
method signInWithCustomToken
signInWithCustomToken: (token: string) => Promise<UserCredential>;
Asynchronously signs in using a custom token.
Custom tokens are used to integrate Firebase Auth with existing auth systems, and must be generated by the auth backend.
Fails with an error if the token is invalid, expired, or not accepted by the Firebase Auth service.
Error Codes auth/custom-token-mismatch Thrown if the custom token is for a different Firebase App. auth/invalid-custom-token Thrown if the custom token format is incorrect.
Parameter token
The custom token to sign in with.
Example 1
firebase.auth().signInWithCustomToken(token).catch(function(error) {// Handle Errors here.var errorCode = error.code;var errorMessage = error.message;if (errorCode === 'auth/invalid-custom-token') {alert('The token you provided is not valid.');} else {console.error(error);}});
method signInWithEmailAndPassword
signInWithEmailAndPassword: ( email: string, password: string) => Promise<UserCredential>;
Asynchronously signs in using an email and password.
Fails with an error if the email address and password do not match.
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: firebase.auth.Auth.createUserWithEmailAndPassword.
Error Codes auth/invalid-email Thrown if the email address is not valid. auth/user-disabled Thrown if the user corresponding to the given email has been disabled. auth/user-not-found Thrown if there is no user corresponding to the given email. auth/wrong-password Thrown if the password is invalid for the given email, or the account corresponding to the email does not have a password set.
Parameter email
The users email address.
Parameter password
The users password.
Example 1
firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {// Handle Errors here.var errorCode = error.code;var errorMessage = error.message;if (errorCode === 'auth/wrong-password') {alert('Wrong password.');} else {alert(errorMessage);}console.log(error);});
method signInWithEmailLink
signInWithEmailLink: ( email: string, emailLink?: string) => Promise<UserCredential>;
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.
Note: Confirm the link is a sign-in email link before calling this method firebase.auth.Auth.isSignInWithEmailLink.
Error Codes auth/expired-action-code Thrown if OTP in email link expires. auth/invalid-email Thrown if the email address is not valid. auth/user-disabled Thrown if the user corresponding to the given email has been disabled.
Parameter email
The email account to sign in with.
Parameter emailLink
The optional link which contains the OTP needed to complete the sign in with email link. If not specified, the current URL is used instead.
Example 1
firebase.auth().signInWithEmailLink(email, emailLink).catch(function(error) {// Some error occurred, you can inspect the code: error.code// Common errors could be invalid email and invalid or expired OTPs.});
method signInWithPhoneNumber
signInWithPhoneNumber: ( phoneNumber: string, applicationVerifier: ApplicationVerifier) => Promise<ConfirmationResult>;
Asynchronously signs in using a phone number. This method sends a code via SMS to the given phone number, and returns a firebase.auth.ConfirmationResult. After the user provides the code sent to their phone, call firebase.auth.ConfirmationResult.confirm with the code to sign the user in.
For abuse prevention, this method also requires a firebase.auth.ApplicationVerifier. The Firebase Auth SDK includes a reCAPTCHA-based implementation, firebase.auth.RecaptchaVerifier.
Error Codes auth/captcha-check-failed Thrown if the reCAPTCHA response token was invalid, expired, or if this method was called from a non-whitelisted domain. auth/invalid-phone-number Thrown if the phone number has an invalid format. auth/missing-phone-number Thrown if the phone number is missing. auth/quota-exceeded Thrown if the SMS quota for the Firebase project has been exceeded. auth/user-disabled Thrown if the user corresponding to the given phone number has been disabled. auth/operation-not-allowed Thrown if you have not enabled the provider in the Firebase Console. Go to the Firebase Console for your project, in the Auth section and the Sign in Method tab and configure the provider.
Parameter phoneNumber
The user's phone number in E.164 format (e.g. +16505550101).
Parameter applicationVerifier
Example 1
// 'recaptcha-container' is the ID of an element in the DOM.var applicationVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');firebase.auth().signInWithPhoneNumber(phoneNumber, applicationVerifier).then(function(confirmationResult) {var verificationCode = window.prompt('Please enter the verification ' +'code that was sent to your mobile device.');return confirmationResult.confirm(verificationCode);}).catch(function(error) {// Handle Errors here.