Skip to main content

Overview

By default, app.auth() returns the GoTrue auth client for sign-up, sign-in, sessions, third-party identities, and multi-factor authentication. Every call returns { data, error }. error is null on success and an AuthError on failure. With init({ throw: true }), auth failures are thrown instead.

Note

authMode is a parameter of cloudbase.init. It selects the app.auth() implementation:

authMode?: 'supabase' | 'cloudbase' // default 'supabase'
authModeClientDescription
supabaseGoTrueDefault. This page documents this mode
cloudbaseCloudBase AuthCompatibility mode. Same app.auth() as v3 authentication

Basic examples​

Create a Publishable Key in CloudBase Platform / API keys. app.auth() and app.auth are the same client. The examples below use app.auth().

import cloudbase from "@cloudbase/js-sdk";

const app = cloudbase.init({
env: "your-env-id",
region: "ap-shanghai",
accessKey: "your-publishable-key",
auth: {
detectSessionInUrl: true, // default is true; set false to turn it off
},
});

const auth = app.auth();

Sign-in​

signUp​

signUp(credentials: SignUpWithPasswordCredentials): Promise<AuthResponse>

Signs up with an email or a phone number and a password. Provide one of email or phone. Phone numbers use the country code plus phone number format, for example +8613800138000.

When confirmation is enabled, user is set and session is null. Finish confirmation with verifyOtp or the email link. When confirmation is disabled, a successful sign-up stores the session and emits SIGNED_IN.

options.data is stored in user_metadata. options.emailRedirectTo applies only to email. options.channel applies only to phone and is sms or whatsapp, defaulting to sms.

Parameters

credentials
SignUpWithPasswordCredentials

Response

Promise
AuthResponse

Example

const { data, error } = await auth.signUp({
email: "user@example.com",
password: "securePassword123",
options: {
data: { name: "Ada" },
emailRedirectTo: "https://example.com/welcome",
},
});

signInAnonymously​

signInAnonymously(credentials?: SignInAnonymouslyCredentials): Promise<AuthResponse>

Creates an anonymous user and a session. options.data is stored in user_metadata. user.is_anonymous is true.

Parameters

credentials
SignInAnonymouslyCredentials

Response

Promise
AuthResponse

Example

const { data, error } = await auth.signInAnonymously();

signInWithPassword​

signInWithPassword(credentials: SignInWithPasswordCredentials): Promise<AuthTokenResponsePassword>

Signs in with an email or phone number and a password. Usernames are not accepted. A weak password can add weakPassword to a successful result.

Parameters

credentials
SignInWithPasswordCredentials

Response

Promise
AuthTokenResponsePassword

Example

const { data, error } = await auth.signInWithPassword({
email: "user@example.com",
password: "securePassword123",
});

signInWithOtp​

signInWithOtp(credentials: SignInWithPasswordlessCredentials): Promise<AuthOtpResponse>

Sends a one-time code or magic link to an email address or phone number. This call only sends the code. It does not create a session. After the user submits the code, call verifyOtp.

options.shouldCreateUser defaults to true. Set it to false to refuse creating an account that does not exist. options.emailRedirectTo is the redirect URL in the email link.

Parameters

credentials
SignInWithPasswordlessCredentials

Response

Promise
AuthOtpResponse

Example

const { error } = await auth.signInWithOtp({
email: "user@example.com",
options: { shouldCreateUser: true },
});

const verified = await auth.verifyOtp({
email: "user@example.com",
token: "123456",
type: "email",
});

verifyOtp​

verifyOtp(params: VerifyOtpParams): Promise<AuthResponse>

Verifies an email or phone code, or the token_hash from an email link. A successful call stores the session.

Common email type values are signup, invite, magiclink, recovery, email_change, and email. Common phone type values are sms and phone_change.

Parameters

params
VerifyOtpParams

Response

Promise
AuthResponse

Example

const { data, error } = await auth.verifyOtp({
email: "user@example.com",
token: "123456",
type: "email",
});

signInWithOAuth​

signInWithOAuth(credentials: SignInWithOAuthCredentials): Promise<OAuthResponse>

Redirects to a third-party OAuth provider. Browsers redirect immediately unless options.skipBrowserRedirect is true, in which case use the returned data.url.

Note

The Publishable Key passed to cloudbase.init({ accessKey }) is sent as the apikey header. auth.detectSessionInUrl is on by default and restores the session from the URL after the redirect. Set it to false to turn that off. The default flow is implicit, and the callback parameters are in the URL hash. For PKCE, set auth.flowType: 'pkce'. See exchangeCodeForSession.

Restoring the session emits SIGNED_IN. provider is a built-in provider or a custom OIDC provider in the form custom:<id>.

Parameters

credentials
SignInWithOAuthCredentials

Response

Promise
OAuthResponse

Example

const { data, error } = await auth.signInWithOAuth({
provider: "github",
options: {
redirectTo: window.location.origin,
scopes: "read:user user:email",
},
});

exchangeCodeForSession​

exchangeCodeForSession(authCode: string, options?: { flowId?: string }): Promise<AuthTokenResponse>

Exchanges the code query parameter for a session in the PKCE (Proof Key for Code Exchange) flow.

When detectSessionInUrl is on (the default) and auth.flowType is 'pkce', the SDK exchanges the code during initialization. Do not call this method.

Call it when detectSessionInUrl is false, or when the authorization code is not on the current page URL. When several PKCE flows run at once, pass the matching options.flowId.

The default flowType is 'implicit', which does not use this method. The two flows differ as follows:

FlowWhat the callback containsHow sign-in completes
implicitTokens, in the URL hashAfter the redirect, detectSessionInUrl stores the session
PKCEcode, in the query stringWith flowType set to 'pkce' and detectSessionInUrl on, the SDK exchanges the code. Call this method when automatic detection is off

Parameters

authCode
string

code query parameter from the PKCE callback URL

options
Object

Return data

Response

Promise
AuthTokenResponse

Example

// When detectSessionInUrl is false, read code and exchange it yourself
const code = new URL(window.location.href).searchParams.get("code");
const { data, error } = await auth.exchangeCodeForSession(code);

signInWithIdToken​

signInWithIdToken(credentials: SignInWithIdTokenCredentials): Promise<AuthTokenResponse>

Signs in with an OIDC ID token issued by a third party. provider supports google, apple, and others, or custom:<id> for a custom OAuth provider. The ID token iss claim must match that provider. If the token contains nonce or at_hash, also pass the matching nonce or access_token.

Parameters

credentials
SignInWithIdTokenCredentials

Response

Promise
AuthTokenResponse

Example

const { data, error } = await auth.signInWithIdToken({
provider: "google",
token: idToken,
nonce,
});

signInWithSAML​

signInWithSAML(credentials: SignInWithProviderUriCredentials): Promise<ProviderUriResponse>

Starts sign-in with a SAML identity source configured in the console. The SDK requests GET /auth/v1/provider/uri and, in a browser, redirects to the returned address.

When options.skipBrowserRedirect is true, the browser stays put. Use the returned data.url.

options.redirectTo is the page to open after sign-in. When omitted, the SDK uses the current page. The value sent to the server keeps only the origin and pathname. Query and hash are dropped. Outside a browser, pass this field. Otherwise the request has no redirect_uri.

options.state is sent unchanged. When omitted, the SDK generates one. The result does not include data.flowId.

Each non-empty entry in options.queryParams is sent as other_params[key].

Parameters

credentials
SignInWithProviderUriCredentials

Response

Promise
ProviderUriResponse

Example

const { data, error } = await auth.signInWithSAML({
providerId: "saml-provider-id",
options: { redirectTo: "https://example.com/welcome" },
});

signInWithSSO​

signInWithSSO(params: SignInWithSSO): Promise<SSOResponse>

Starts SSO with a provider UUID or an organization email domain. Browsers redirect by default. Set options.skipBrowserRedirect to true to receive data.url and redirect yourself.

Parameters

params
SignInWithSSO

Response

Promise
SSOResponse

Example

const { data, error } = await auth.signInWithSSO({
domain: "company.com",
options: { redirectTo: window.location.origin },
});

signInWithCAS​

signInWithCAS(credentials: SignInWithProviderUriCredentials): Promise<ProviderUriResponse>

Starts sign-in with a CAS identity source configured in the console. The request and redirect match signInWithSAML.

The browser returns to redirect_uri?state=...&ticket=.... state carries a flow id, which the method returns as data.flowId. When a redirect_uri is available, it also stores this login in client storage.

detectSessionInUrl is on by default. On the next load, if that record is still available, the SDK exchanges the ticket in the URL for a session and removes the record. Success emits SIGNED_IN.

To exchange the ticket yourself, create the client with detectSessionInUrl: false or skipAutoInitialize: true, then call exchangeTicketForSession. After the automatic exchange, the ticket is already used and the stored fields are gone.

options.state also acts as the flow id:

  • When omitted, the SDK generates a flow id and uses it as state
  • A value matching [A-Za-z0-9_-]{8,64} is the flow id
  • Any other value gets a new flow id, prefixed to the original value with .. The flow id can still be read from state after the redirect

redirectTo, skipBrowserRedirect, and queryParams match signInWithSAML.

Parameters

credentials
SignInWithProviderUriCredentials

Response

Promise
ProviderUriResponse

Example

const { data, error } = await auth.signInWithCAS({
providerId: "cas-provider-id",
});
// data.flowId selects this sign-in when exchanging the ticket

exchangeTicketForSession​

exchangeTicketForSession(ticket: string, options?: ExchangeTicketForSessionOptions): Promise<AuthTokenResponse>

Exchanges a CAS service ticket for a session. The SDK requests POST /auth/v1/signin/with/provider, stores the session, and emits SIGNED_IN.

When detectSessionInUrl is on, the SDK already exchanges the ticket during initialization. Do not call this method.

Call it when detectSessionInUrl is false, or when the ticket is not on the current page URL. When several CAS flows run at once, pass the matching options.flowId.

Omitted providerId, redirectUri, and state are read from the login stored by signInWithCAS. When flowId is set, the URL state is not used to find that record. When flowId is omitted, the SDK reads it from the current URL state, then falls back to the most recent record.

The record can be missing after a change of tab, origin, or device, when session persistence is off, or after the callback has already been handled. Pass the fields explicitly in those cases.

redirectUri must be the address sent to the identity source: origin plus pathname, without ticket. Auth rebuilds the CAS service as redirectUri?state=..., which is the URL the ticket was issued for.

Parameters

ticket
string

ticket query parameter from the CAS callback URL

options
Object

Return data

Response

Promise
AuthTokenResponse

Example

// Create the client with detectSessionInUrl: false, then read ticket yourself
const ticket = new URL(window.location.href).searchParams.get("ticket");
if (ticket) {
const { data, error } = await auth.exchangeTicketForSession(ticket);
}

signInWithCustomTicket​

signInWithCustomTicket(credentials: SignInWithCustomTicketCredentials): Promise<AuthTokenResponse>

Signs in with a custom login ticket. On success the session is stored and SIGNED_IN is emitted.

ticket has the form <keyId>/<anything>/<JWT> and is signed with the business private key. That key must match the custom-login public key configured in the console. The server signs it with createTicket.

Parameters

credentials
SignInWithCustomTicketCredentials

Response

Promise
AuthTokenResponse

Example

const { data, error } = await auth.signInWithCustomTicket({
ticket,
});

createTicket​

async auth.createTicket(uid: string, options?: ICreateTicketOpts): Promise<string>

Creates a custom login credential Ticket, using an RSA private key to sign a JWT. The client can exchange this Ticket for a login state.

  • Only applicable to Node.js server-side (cloud functions, CloudBase Run, self-hosted servers, etc.). The private key must never be written into front-end environments such as mini programs or H5
  • Before use, you must pass the custom login private key credentials during init. This field is a top-level configuration of cloudbase.init(), belonging to Node.js-specific parameters. Do not place it under auth
  • Go to CloudBase Platform / Identity Authentication / Login Methods and download the private key file via "Custom Login"
  • You need to install the dependency: npm install jsonwebtoken

The credentials object contains the following fields (all from the downloaded private key file tcb_custom_login.json, no need to fill them in manually):

FieldDescription
env_idThe environment ID that the private key belongs to
private_key_idThe private key identifier, carried in the issued Ticket for verification
private_keyThe RSA private key content, used to sign the JWT. Please keep it safe and never leak it

Parameters

uid
string

Developer-defined unique user ID (4-32 characters, supports letters, numbers, and some special characters)

options
ICreateTicketOpts

Optional configuration

Response

Promise
string

Returns a ticket string in the format "{private_key_id}/@@/{jwt_token}"

Example

const cloudbase = require("@cloudbase/js-sdk");

const app = cloudbase.init({
env: "your-env-id",
// credentials is a top-level config of init(); do not place it under auth
credentials: require("/path/to/tcb_custom_login.json"),
});

exports.main = async (event, context) => {
const ticket = await app.auth.createTicket("custom-user-id-123", {
refresh: 3600 * 1000, // Refresh every 1 hour
});
console.log(ticket);
// Return the ticket to the client; the client calls signInWithCustomTicket to complete login
};
Security Notice

The private_key in credentials is a sensitive credential that verifies administrator identity. It can only be used on the server side and must never be written into mini programs, H5, or any front-end environment variables, to prevent leakage.

signInWithOpenId​

signInWithOpenId(credentials?: SignInWithOpenIdCredentials): Promise<AuthTokenResponse>

Signs in with a WeChat OpenID. On success the session is stored and SIGNED_IN is emitted.

Mini programs, third-party platforms, official accounts, and open-platform apps pass the code from wx.login and the matching appId. CloudBase passwordless login can omit code; the gateway fills in the identity headers. That access token may have no refresh token, and the session cannot be refreshed.

Parameters

credentials
SignInWithOpenIdCredentials

Response

Promise
AuthTokenResponse

Example

const { data, error } = await auth.signInWithOpenId({
code: "wx-login-code",
appId: "wx-app-id",
});

signInWithPhoneAuth​

signInWithPhoneAuth(credentials: SignInWithPhoneAuthCredentials): Promise<AuthTokenResponse>

Signs in with a WeChat mini program phone-number authorization. phoneCode comes from wx.getPhoneNumber. On success the session is stored and SIGNED_IN is emitted.

providerId is stored on the authorization ticket and defaults to appId.

Parameters

credentials
SignInWithPhoneAuthCredentials

Response

Promise
AuthTokenResponse

Example

const { data, error } = await auth.signInWithPhoneAuth({
phoneCode: "wx-phone-code",
appId: "wx-app-id",
});

Session​

Sessions are stored locally and the access token is refreshed automatically. The storage key for an environment is cloudbase-auth-js-<env>.

getSession​

getSession(): Promise<{ data: { session: Session | null }; error: AuthError | null }>

Reads the local session. When the access token is close to expiry, it is refreshed first and the new session is returned. data.session is null when nobody is signed in.

const { data, error } = await auth.getSession();
const token = data.session?.access_token;

refreshSession​

refreshSession(currentSession?: { refresh_token: string }): Promise<AuthResponse>

Exchanges a refresh token for a new session. When called with no argument, it uses the refresh token from the local session.

const { data, error } = await auth.refreshSession();

setSession​

setSession(currentSession: { access_token: string; refresh_token: string }): Promise<AuthResponse>

Restores a session from an existing access token and refresh token, and writes it to local storage.

Parameters

currentSession
object

Response

Promise
AuthResponse

Example

const { data, error } = await auth.setSession({
access_token,
refresh_token,
});

signOut​

signOut(options?: { scope?: "global" | "local" | "others" }): Promise<{ error: AuthError | null }>

Signs out. scope defaults to global.

scopeBehavior
globalRevokes every session for the account and clears the local session
localClears only the local session
othersRevokes every session except the current one. This page does not receive SIGNED_OUT
const { error } = await auth.signOut({ scope: "local" });

User​

getUser​

getUser(jwt?: string): Promise<UserResponse>

Loads the current user from the auth service. Pass jwt to validate that token. Otherwise the access token from the local session is used. This method always calls the server, so it is the right call when you need the latest confirmation state or identities.

const { data, error } = await auth.getUser();
console.log(data.user?.email, data.user?.user_metadata);

updateUser​

updateUser(attributes: UserAttributes, options?: { emailRedirectTo?: string }): Promise<UserResponse>

Updates the current user's email, phone, password, or user_metadata. A session is required.

A new email or phone takes effect only after the user verifies it. Until then the pending value is user.new_email or user.new_phone. If a password change requires reauthentication, call reauthenticate and pass the code as nonce.

Parameters

attributes
UserAttributes
options
Object

Return data

Response

Promise
UserResponse

Example

const { data, error } = await auth.updateUser({
data: { name: "Ada" },
});

Identities​

getUserIdentities​

getUserIdentities(): Promise<{ data: { identities: UserIdentity[] } | null; error: AuthError | null }>

Returns the identities linked to the current user. A session is required.

const { data, error } = await auth.getUserIdentities();
data?.identities.forEach((identity) => {
console.log(identity.provider, identity.identity_id);
});

linkIdentity​

linkIdentity(credentials: SignInWithOAuthCredentials): Promise<OAuthResponse>
linkIdentity(credentials: SignInWithIdTokenCredentials): Promise<AuthTokenResponse>

Links an OAuth provider or an ID token identity to the current user. OAuth linking redirects as well. detectSessionInUrl is on by default and restores the session after the redirect. Set it to false to turn that off. The arguments match signInWithOAuth and signInWithIdToken.

const { data, error } = await auth.linkIdentity({
provider: "github",
options: { redirectTo: window.location.href },
});

unlinkIdentity​

unlinkIdentity(identity: UserIdentity): Promise<{ data: {} | null; error: AuthError | null }>

Unlinks one identity. Pass the object returned by getUserIdentities, not a provider name. If it is the account's only identity, the server returns single_identity_not_deletable.

const { data, error } = await auth.getUserIdentities();
const github = data?.identities.find((item) => item.provider === "github");
if (github) {
await auth.unlinkIdentity(github);
}

Password​

resetPasswordForEmail​

resetPasswordForEmail(email: string, options?: { redirectTo?: string; captchaToken?: string }): Promise<{ data: {} | null; error: AuthError | null }>

Sends a password-recovery email. When the user opens the link, the client emits PASSWORD_RECOVERY. Call updateUser({ password }) in that callback to set the new password.

const { error } = await auth.resetPasswordForEmail("user@example.com", {
redirectTo: "https://example.com/reset-password",
});

auth.onAuthStateChange(async (event) => {
if (event === "PASSWORD_RECOVERY") {
await auth.updateUser({ password: "new-password" });
}
});

reauthenticate​

reauthenticate(): Promise<AuthResponse>

Sends a code to the user's confirmed email or phone before a sensitive change such as a password update. Pass that code as nonce to updateUser.

const { error } = await auth.reauthenticate();

Verification​

resend​

resend(credentials: ResendParams): Promise<AuthOtpResponse>

Resends a sign-up or contact-change code.

typeRequired fieldMeaning
signupemailResend the sign-up confirmation
email_changeemailResend the email-change confirmation
smsphoneResend an SMS code
phone_changephoneResend the phone-change confirmation
const { error } = await auth.resend({
type: "signup",
email: "user@example.com",
});

Verify the code with verifyOtp.


Multi-factor authentication​

auth.mfa manages TOTP, phone, and WebAuthn factors. A newly enrolled factor is unverified. After verification it becomes verified, the current session is promoted to aal2, and other sessions are signed out.

After sign-in, if getAuthenticatorAssuranceLevel reports nextLevel aal2 and currentLevel aal1, call challenge and then verify.

mfa.enroll​

auth.mfa.enroll(params: MFAEnrollParams): Promise<AuthMFAEnrollResponse>

Enrolls an unverified factor. A TOTP enrollment returns totp.qr_code, totp.secret, and totp.uri. Show the QR code or secret in the user's authenticator app.

Parameters

params
MFAEnrollParams

Response

Promise
AuthMFAEnrollResponse

Example

const { data, error } = await auth.mfa.enroll({
factorType: "totp",
friendlyName: "Authenticator",
issuer: "CloudBase",
});

mfa.challenge​

auth.mfa.challenge(params: { factorId: string }): Promise<AuthMFAChallengeResponse>

Starts a challenge for a factor. A phone factor sends an SMS. The returned id is the challenge id.

const { data, error } = await auth.mfa.challenge({ factorId });

mfa.verify​

auth.mfa.verify(params: MFAVerifyParams): Promise<AuthMFAVerifyResponse>

Submits the code from an authenticator app or an SMS. On success the session is promoted to aal2 and MFA_CHALLENGE_VERIFIED is emitted.

const { data, error } = await auth.mfa.verify({
factorId,
challengeId,
code: "123456",
});

mfa.challengeAndVerify​

auth.mfa.challengeAndVerify(params: { factorId: string; code: string }): Promise<AuthMFAVerifyResponse>

Challenges and verifies a TOTP factor in one call. Phone factors need the user to receive the SMS first, so call challenge and verify separately.

const { data, error } = await auth.mfa.challengeAndVerify({
factorId,
code: "123456",
});

mfa.unenroll​

auth.mfa.unenroll(params: { factorId: string }): Promise<AuthMFAUnenrollResponse>

Deletes one factor.

const { error } = await auth.mfa.unenroll({ factorId });

mfa.listFactors​

auth.mfa.listFactors(): Promise<AuthMFAListFactorsResponse>

Lists the current user's factors, grouped as totp, phone, and all, including verified and unverified factors.

const { data, error } = await auth.mfa.listFactors();
const factorId = data?.totp[0]?.id;

mfa.getAuthenticatorAssuranceLevel​

auth.mfa.getAuthenticatorAssuranceLevel(): Promise<AuthMFAGetAuthenticatorAssuranceLevelResponse>

Reads the authenticator assurance level of the current session. currentLevel is the current level. nextLevel is the level the enrolled factors can reach. When currentLevel is "aal1" and nextLevel is "aal2", start an MFA challenge.

const { data, error } = await auth.mfa.getAuthenticatorAssuranceLevel();
if (data?.nextLevel === "aal2" && data.currentLevel !== data.nextLevel) {
// start mfa.challenge
}

Utilities​

onAuthStateChange​

onAuthStateChange(
callback: (event: AuthChangeEvent, session: Session | null) => void
): { data: { subscription: { unsubscribe: () => void } } }

Subscribes to auth state changes. The callback receives the event name and the session. There is no third argument.

EventWhen
INITIAL_SESSIONThe client finished restoring the local session
SIGNED_INSigned in, or the session was restored from an OAuth callback
SIGNED_OUTThe current session was cleared
TOKEN_REFRESHEDThe access token was refreshed
USER_UPDATEDUser profile was updated
PASSWORD_RECOVERYThe user returned from a password-recovery link
MFA_CHALLENGE_VERIFIEDThe MFA challenge was verified
const { data } = auth.onAuthStateChange((event, session) => {
if (event === "SIGNED_OUT") {
console.log("signed out");
}
});

getClaims​

getClaims(jwt?: string): Promise<{
data: { claims: JwtPayload; header: JwtHeader; signature: Uint8Array } | null;
error: AuthError | null;
}>

Verifies a JWT and returns its claims. When jwt is omitted, the access token from the current session is used. Asymmetric JWTs are verified with JWKS.

const { data, error } = await auth.getClaims();
console.log(data?.claims.sub, data?.claims.role);

Error codes​

error.code is the server error code, error.status is the HTTP status, and error.message is the description. The server can return codes that are not listed here.

Sign-in and sign-up​

codeMeaning
invalid_credentialsEmail, phone, or password is incorrect
email_not_confirmedEmail is not confirmed
phone_not_confirmedPhone number is not confirmed
email_existsEmail is already registered
phone_existsPhone number is already registered
user_already_existsUser already exists
user_not_foundUser does not exist
user_bannedUser is banned
signup_disabledSign-up is disabled
email_provider_disabledEmail sign-in is disabled
phone_provider_disabledPhone sign-in is disabled
anonymous_provider_disabledAnonymous sign-in is disabled
provider_disabledThis identity provider is disabled
weak_passwordPassword is too weak
same_passwordThe new password matches the current password

OTP and session​

codeMeaning
otp_expiredOTP has expired
otp_disabledOTP sign-in is disabled
over_request_rate_limitToo many requests
over_email_send_rate_limitToo many emails
over_sms_send_rate_limitToo many SMS messages
sms_send_failedSMS delivery failed
session_not_foundSession was not found
session_expiredSession has expired
refresh_token_not_foundRefresh token was not found
refresh_token_already_usedRefresh token was already used
bad_jwtJWT is invalid
bad_code_verifierPKCE code verifier does not match
flow_state_expiredThe sign-in flow has expired
reauthentication_neededReauthentication is required before this change
reauthentication_not_validThe reauthentication code is invalid
reauth_nonce_missingReauthentication nonce is missing

OAuth, identities, and MFA​

codeMeaning
oauth_provider_not_supportedThis OAuth provider is not supported
bad_oauth_stateOAuth state is invalid
bad_oauth_callbackOAuth callback is invalid
identity_already_existsThis identity is already linked to another user
identity_not_foundIdentity was not found
single_identity_not_deletableThe last identity cannot be removed
manual_linking_disabledManual identity linking is disabled
mfa_verification_failedMFA code is incorrect
mfa_challenge_expiredMFA challenge has expired
mfa_factor_not_foundMFA factor was not found
too_many_enrolled_mfa_factorsToo many enrolled MFA factors
insufficient_aalAuthenticator assurance level is too low

Types​

User​

interface User {
id: string;
email?: string;
phone?: string;
role?: string;
aud: string;
app_metadata: { provider?: string; providers?: string[]; [key: string]: any };
user_metadata: { [key: string]: any };
identities?: UserIdentity[];
factors?: Factor[];
is_anonymous?: boolean;
is_sso_user?: boolean;
confirmed_at?: string;
email_confirmed_at?: string;
phone_confirmed_at?: string;
last_sign_in_at?: string;
created_at: string;
updated_at?: string;
new_email?: string;
new_phone?: string;
}

Session​

interface Session {
access_token: string;
refresh_token: string;
expires_in: number;
expires_at?: number;
token_type: "bearer";
user: User;
provider_token?: string | null;
provider_refresh_token?: string | null;
}

UserIdentity​

interface UserIdentity {
id: string;
user_id: string;
identity_id: string;
provider: string;
identity_data?: { [key: string]: any };
created_at?: string;
last_sign_in_at?: string;
updated_at?: string;
}

AuthError​

class AuthError extends Error {
code: string | undefined;
status: number | undefined;
name: "AuthError" | "AuthApiError";
}

AuthChangeEvent​

type AuthChangeEvent =
| "INITIAL_SESSION"
| "PASSWORD_RECOVERY"
| "SIGNED_IN"
| "SIGNED_OUT"
| "TOKEN_REFRESHED"
| "USER_UPDATED"
| "MFA_CHALLENGE_VERIFIED";