Hi there! Are you looking for the official Deno documentation? Try docs.deno.com for all your Deno learning needs.

GoTrueClient

import { GoTrueClient } from "https://esm.sh/@supabase/supabase-js@2.108.1/dist/index.d.mts";
class GoTrueClient {
constructor(options: GoTrueClientOptions);
private __loadSession;
private _acquireLock;
private _approveAuthorization;
private _autoRefreshTokenTick;
private _callRefreshToken;
private _challenge;
private _challengeAndVerify;
private _debug;
private _deletePasskey;
private _denyAuthorization;
private _emitInitialSession;
private _enroll;
private _exchangeCodeForSession;
private _getAuthenticatorAssuranceLevel;
private _getAuthorizationDetails;
private _getSessionFromURL;
private _getUrlForProvider;
private _getUser;
private _handleProviderSignIn;
private _handleVisibilityChange;
private _initialize;
private _isImplicitGrantCallback;
private _isPKCECallback;
private _isValidSession;
private _listFactors;
private _listOAuthGrants;
private _listPasskeys;
private _logPrefix;
private _notifyAllSubscribers;
private _onVisibilityChanged;
private _reauthenticate;
private _recoverAndRefresh;
private _refreshAccessToken;
private _removeSession;
private _removeVisibilityChangedCallback;
private _returnResult;
private _revokeOAuthGrant;
private _saveSession;
private _startAutoRefresh;
private _startPasskeyAuthentication;
private _startPasskeyRegistration;
private _stopAutoRefresh;
private _unenroll;
private _updatePasskey;
private _useSession;
private _verify;
private _verifyPasskeyAuthentication;
private _verifyPasskeyRegistration;
private fetchJwk;
private instanceID;
private linkIdentityIdToken;
private linkIdentityOAuth;
private signInWithEthereum;
private signInWithSolana;
protected _sessionRemovalEpoch: number;
protected autoRefreshTicker: ReturnType<setInterval> | null;
protected autoRefreshTickTimeout: ReturnType<setTimeout> | null;
protected autoRefreshToken: boolean;
protected broadcastChannel: BroadcastChannel | null;
protected detectSessionInUrl: boolean | ((url: URL, params: {
[parameter: string]: string;
}
) => boolean
)
;
protected experimental: ExperimentalFeatureFlags;
protected fetch: Fetch;
protected flowType: AuthFlowType;
protected hasCustomAuthorizationHeader: boolean;
protected headers: {
[key: string]: string;
}
;
protected initializePromise: Promise<InitializeResult> | null;
protected get jwks(): {
keys: JWK[];
}
;
protected set jwks(value: {
keys: JWK[];
}
);
protected get jwks_cached_at(): number;
protected set jwks_cached_at(value: number);
protected lock: LockFunc | null;
protected lockAcquired: boolean;
protected lockAcquireTimeout: number;
protected logDebugMessages: boolean;
protected logger: (message: string, ...args: any[]) => void;
protected memoryStorage: {
[key: string]: string;
}
| null;
protected pendingInLock: Promise<any>[];
protected persistSession: boolean;
protected refreshingDeferred: Deferred<CallRefreshTokenResult> | null;
protected stateChangeEmitters: Map<string | symbol, Subscription>;
protected storage: SupportedStorage;
protected storageKey: string;
protected suppressGetSessionWarning: boolean;
protected throwOnError: boolean;
protected url: string;
protected userStorage: SupportedStorage | null;
protected visibilityChangedCallback: (() => Promise<any>) | null;
passkey: AuthPasskeyApi;
 
protected _refreshSession(currentSession?: {
refresh_token: string;
}
): Promise<AuthResponse>;
protected _setSession(currentSession: {
access_token: string;
refresh_token: string;
}
): Promise<AuthResponse>;
protected _signOut({ scope }?: SignOut): Promise<{
error: AuthError | null;
}
>
;
protected _updateUser(attributes: UserAttributes, options?: {
emailRedirectTo?: string | undefined;
}
): Promise<UserResponse>;
dispose(): Promise<void>;
exchangeCodeForSession(authCode: string): Promise<AuthTokenResponse>;
getClaims(jwt?: string, options?: {
keys?: JWK[];
allowExpired?: boolean;
jwks?: {
keys: JWK[];
}
;
}
): Promise<{
data: {
claims: JwtPayload;
header: JwtHeader;
signature: Uint8Array;
}
;
error: null;
}
| {
data: null;
error: AuthError;
}
| {
data: null;
error: null;
}
>
;
getSession(): Promise<{
data: {
session: Session;
}
;
error: null;
}
| {
data: {
session: null;
}
;
error: AuthError;
}
| {
data: {
session: null;
}
;
error: null;
}
>
;
getUser(jwt?: string): Promise<UserResponse>;
getUserIdentities(): Promise<{
data: {
identities: UserIdentity[];
}
;
error: null;
}
| {
data: null;
error: AuthError;
}
>
;
initialize(): Promise<InitializeResult>;
isThrowOnErrorEnabled(): boolean;
linkIdentity(credentials: SignInWithOAuthCredentials): Promise<OAuthResponse>;
linkIdentity(credentials: SignInWithIdTokenCredentials): Promise<AuthTokenResponse>;
onAuthStateChange(callback: (event: AuthChangeEvent, session: Session | null) => void): {
data: {
subscription: Subscription;
}
;
}
;
onAuthStateChange(callback: (event: AuthChangeEvent, session: Session | null) => Promise<void>): {
data: {
subscription: Subscription;
}
;
}
;
reauthenticate(): Promise<AuthResponse>;
refreshSession(currentSession?: {
refresh_token: string;
}
): Promise<AuthResponse>;
registerPasskey(credentials?: RegisterPasskeyCredentials): Promise<AuthPasskeyRegistrationVerifyResponse>;
resend(credentials: ResendParams): Promise<AuthOtpResponse>;
resetPasswordForEmail(email: string, options?: {
redirectTo?: string;
captchaToken?: string;
}
): Promise<{
data: {};
error: null;
}
| {
data: null;
error: AuthError;
}
>
;
setSession(currentSession: {
access_token: string;
refresh_token: string;
}
): Promise<AuthResponse>;
signInAnonymously(credentials?: SignInAnonymouslyCredentials): Promise<AuthResponse>;
signInWithIdToken(credentials: SignInWithIdTokenCredentials): Promise<AuthTokenResponse>;
signInWithOAuth(credentials: SignInWithOAuthCredentials): Promise<OAuthResponse>;
signInWithOtp(credentials: SignInWithPasswordlessCredentials): Promise<AuthOtpResponse>;
signInWithPasskey(credentials?: SignInWithPasskeyCredentials): Promise<AuthPasskeyAuthenticationVerifyResponse>;
signInWithPassword(credentials: SignInWithPasswordCredentials): Promise<AuthTokenResponsePassword>;
signInWithSSO(params: SignInWithSSO): Promise<SSOResponse>;
signInWithWeb3(credentials: Web3Credentials): Promise<{
data: {
session: Session;
user: User;
}
;
error: null;
}
| {
data: {
session: null;
user: null;
}
;
error: AuthError;
}
>
;
signOut(options?: SignOut): Promise<{
error: AuthError | null;
}
>
;
signUp(credentials: SignUpWithPasswordCredentials): Promise<AuthResponse>;
startAutoRefresh(): Promise<void>;
stopAutoRefresh(): Promise<void>;
unlinkIdentity(identity: UserIdentity): Promise<{
data: {};
error: null;
}
| {
data: null;
error: AuthError;
}
>
;
updateUser(attributes: UserAttributes, options?: {
emailRedirectTo?: string | undefined;
}
): Promise<UserResponse>;
verifyOtp(params: VerifyOtpParams): Promise<AuthResponse>;
 
static private nextInstanceID;
}

§Constructors

§
new GoTrueClient(options: GoTrueClientOptions)
[src]

Create a new client for use in the browser.

@example

Using supabase-js (recommended)

import { createClient } from '@supabase/supabase-js'

const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key')
const { data, error } = await supabase.auth.getUser()
@example

Standalone import for bundle-sensitive environments

import { GoTrueClient } from '@supabase/auth-js'

const auth = new GoTrueClient({
  url: 'https://xyzcompany.supabase.co/auth/v1',
  headers: { apikey: 'your-publishable-key' },
  storageKey: 'supabase-auth',
})

§Properties

§
__loadSession
[src]

NEVER USE DIRECTLY!

Always use {@link #_useSession}.

§
_acquireLock
[src]

Acquires a global lock based on the storage key.

TODO(v3): remove along with the legacy lock path. Only called when this.lock is non-null (custom lock supplied via constructor). The default lockless path bypasses this entirely.

§
_approveAuthorization
[src]

Approves an OAuth authorization request. Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.

§
_autoRefreshTokenTick
[src]

Runs the auto refresh token tick.

§
_callRefreshToken
[src]
§
_challenge
[src]

{@see GoTrueMFAApi#challenge}

§
_challengeAndVerify
[src]

{@see GoTrueMFAApi#challengeAndVerify}

§
_debug
[src]
§
_deletePasskey
[src]

Delete a passkey.

§
_denyAuthorization
[src]

Denies an OAuth authorization request. Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.

§
_emitInitialSession
[src]
§
_enroll
[src]

{@see GoTrueMFAApi#enroll}

§
_exchangeCodeForSession
[src]
§
_getAuthenticatorAssuranceLevel
[src]

{@see GoTrueMFAApi#getAuthenticatorAssuranceLevel}

§
_getAuthorizationDetails
[src]

Retrieves details about an OAuth authorization request. Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.

Returns authorization details including client info, scopes, and user information. If the response includes only a redirect_url field, it means consent was already given - the caller should handle the redirect manually if needed.

§
_getSessionFromURL
[src]

Gets the session data from a URL string

§
_getUrlForProvider
[src]

Generates the relevant login URL for a third-party provider.

§
_getUser
[src]
§
_handleProviderSignIn
[src]
§
_handleVisibilityChange
[src]

Registers callbacks on the browser / platform, which in-turn run algorithms when the browser window/tab are in foreground. On non-browser platforms it assumes always foreground.

§
_initialize
[src]

IMPORTANT:

  1. Never throw in this method, as it is called from the constructor
  2. Never return a session from this method as it would be cached over the whole lifetime of the client
§
_isImplicitGrantCallback
[src]

Checks if the current URL contains parameters given by an implicit oauth grant flow (https://www.rfc-editor.org/rfc/rfc6749.html#section-4.2)

If detectSessionInUrl is a function, it will be called with the URL and params to determine if the URL should be processed as a Supabase auth callback. This allows users to exclude URLs from other OAuth providers (e.g., Facebook Login) that also return access_token in the fragment.

§
_isPKCECallback
[src]

Checks if the current URL and backing storage contain parameters given by a PKCE flow

§
_isValidSession
[src]
§
_listFactors
[src]

{@see GoTrueMFAApi#listFactors}

§
_listOAuthGrants
[src]

Lists all OAuth grants that the authenticated user has authorized. Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.

§
_listPasskeys
[src]

List all passkeys for the current user.

§
_logPrefix
[src]
§
_notifyAllSubscribers
[src]
§
_onVisibilityChanged
[src]

Callback registered with window.addEventListener('visibilitychange').

§
_reauthenticate
[src]
§
_recoverAndRefresh
[src]

Recovers the session from LocalStorage and refreshes the token Note: this method is async to accommodate for AsyncStorage e.g. in React native.

§
_refreshAccessToken
[src]

Generates a new JWT.

§
_removeSession
[src]
§
_removeVisibilityChangedCallback
[src]

Removes any registered visibilitychange callback.

{@see #startAutoRefresh} {@see #stopAutoRefresh}

§
_returnResult
[src]

Centralizes return handling with optional error throwing. When throwOnError is enabled and the provided result contains a non-nullish error, the error is thrown instead of being returned. This ensures consistent behavior across all public API methods.

§
_revokeOAuthGrant
[src]

Revokes a user's OAuth grant for a specific client. Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.

§
_saveSession
[src]

set currentSession and currentUser process to _startAutoRefreshToken if possible

§
_startAutoRefresh
[src]

This is the private implementation of {@link #startAutoRefresh}. Use this within the library.

§
_startPasskeyAuthentication
[src]

Start passkey authentication. Returns WebAuthn credential request options to pass to navigator.credentials.get().

§
_startPasskeyRegistration
[src]

Start passkey registration for the current authenticated user. Returns WebAuthn credential creation options to pass to navigator.credentials.create().

§
_stopAutoRefresh
[src]

This is the private implementation of {@link #stopAutoRefresh}. Use this within the library.

§
_unenroll
[src]
§
_updatePasskey
[src]

Update a passkey.

§
_useSession
[src]

Use instead of {@link #getSession} inside the library. Loads the session via __loadSession (which may trigger a refresh if the access token is within the expiry margin) and runs fn with the result.

§
_verify
[src]

{@see GoTrueMFAApi#verify}

§
_verifyPasskeyAuthentication
[src]

Verify passkey authentication and create a session. The credential should be the serialized output of navigator.credentials.get().

§
_verifyPasskeyRegistration
[src]

Verify passkey registration with the credential response. The credentialResponse should be the serialized output of navigator.credentials.create().

§
fetchJwk
[src]
§
instanceID
[src]
§
linkIdentityIdToken
[src]
§
linkIdentityOAuth
[src]
§
signInWithEthereum
[src]
§
signInWithSolana
[src]
§
_sessionRemovalEpoch: number
[src]

Monotonic counter incremented at the top of _removeSession, before any await. The commit guard inside _callRefreshToken captures this value before _saveSession and re-checks it after, so a signOut that interleaves inside _saveSession's storage-write awaits is still caught (the post-fetch storage snapshot alone misses that window).

§
autoRefreshTicker: ReturnType<setInterval> | null
[src]
§
autoRefreshTickTimeout: ReturnType<setTimeout> | null
[src]
§
autoRefreshToken: boolean
[src]
§
broadcastChannel: BroadcastChannel | null
[src]

Used to broadcast state change events to other tabs listening.

§
detectSessionInUrl: boolean | ((url: URL, params: {
[parameter: string]: string;
}
) => boolean
)
[src]
§

Opt-in flags for experimental features. Defaults to an empty object. See GoTrueClientOptions.experimental.

§
hasCustomAuthorizationHeader: boolean
[src]
§
headers: {
[key: string]: string;
}
[src]
§
initializePromise: Promise<InitializeResult> | null
[src]

Keeps track of the async client initialization. When null or not yet resolved the auth state is unknown Once resolved the auth state is known and it's safe to call any further client methods. Keep extra care to never reject or throw uncaught errors

§
jwks: {
keys: JWK[];
}
protected
[src]

The JWKS used for verifying asymmetric JWTs

§
jwks_cached_at: number protected
[src]
§
lock: LockFunc | null
[src]

Custom lock function passed via settings.lock. When non-null, every auth operation runs inside _acquireLock. When null (the default), the client uses its lockless coordination (refresh single-flight + commit guard). TODO(v3): remove along with the legacy lock path.

§
lockAcquired: boolean
[src]
§
lockAcquireTimeout: number
[src]

Only consulted when a custom lock is supplied. TODO(v3): remove.

§
logDebugMessages: boolean
[src]
§
logger: (message: string, ...args: any[]) => void
[src]
§
memoryStorage: {
[key: string]: string;
}
| null
[src]
§
pendingInLock: Promise<any>[]
[src]
§
persistSession: boolean
[src]
§
refreshingDeferred: Deferred<CallRefreshTokenResult> | null
[src]
§
stateChangeEmitters: Map<string | symbol, Subscription>
[src]
§
storageKey: string
[src]

The storage key used to identify the values saved in localStorage

§
suppressGetSessionWarning: boolean
[src]
§
throwOnError: boolean
[src]
§
url: string
[src]
§
userStorage: SupportedStorage | null
[src]
§
visibilityChangedCallback: (() => Promise<any>) | null
[src]
§

Namespace for the GoTrue admin methods. These methods should only be used in a trusted server-side environment.

§

Namespace for the MFA methods.

§

Namespace for the OAuth 2.1 authorization server methods. Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. Used to implement the authorization code flow on the consent page.

§

Namespace for passkey methods. Includes lower-level two-step registration/authentication and passkey management.

Requires auth.experimental.passkey: true; otherwise all methods throw.

§Methods

§
_refreshSession(currentSession?: {
refresh_token: string;
}
): Promise<AuthResponse> protected
[src]
§
_setSession(currentSession: {
access_token: string;
refresh_token: string;
}
): Promise<AuthResponse> protected
[src]
§
_signOut({ scope }?: SignOut): Promise<{
error: AuthError | null;
}
>
protected
[src]
§
_updateUser(attributes: UserAttributes, options?: {
emailRedirectTo?: string | undefined;
}
): Promise<UserResponse> protected
[src]
§
dispose(): Promise<void>
[src]

Tears down the client's background work: stops the auto-refresh interval, removes the visibilitychange listener, closes the cross-tab BroadcastChannel, and clears registered onAuthStateChange subscribers.

Call this from cleanup hooks when the client is being replaced before its JS realm is destroyed. React Strict Mode and HMR are the common cases. Any in-flight fetch calls continue to completion and may still write to storage; dispose doesn't abort them or erase storage.

Lifecycle caveat: because in-flight refreshes are not aborted, a disposed instance can still persist a rotated session to storage after dispose() returns. A subsequent createClient against the same storageKey will pick up that session on its next read. If you need strict isolation between client lifecycles, await any pending auth operation before calling dispose() (or change the storageKey for the replacement client).

Safe to call repeatedly.

@example

Cleanup on React unmount

useEffect(() => {
  const client = createClient(...)
  return () => { client.auth.dispose() }
}, [])
§
exchangeCodeForSession(authCode: string): Promise<AuthTokenResponse>
[src]

Log in an existing user by exchanging an Auth Code issued during the PKCE flow.

@example

Exchange Auth Code

supabase.auth.exchangeCodeForSession('34e770dd-9ff9-416c-87fa-43b31d7ef225')
@example
§
getClaims(jwt?: string, options?: {
keys?: JWK[];
allowExpired?: boolean;
jwks?: {
keys: JWK[];
}
;
}
): Promise<{
data: {
claims: JwtPayload;
header: JwtHeader;
signature: Uint8Array;
}
;
error: null;
}
| {
data: null;
error: AuthError;
}
| {
data: null;
error: null;
}
>
[src]

Extracts the JWT claims present in the access token by first verifying the JWT against the server's JSON Web Key Set endpoint /.well-known/jwks.json which is often cached, resulting in significantly faster responses. Prefer this method over {@link #getUser} which always sends a request to the Auth server for each JWT.

If the project is not using an asymmetric JWT signing key (like ECC or RSA) it always sends a request to the Auth server (similar to {@link #getUser}) to verify the JWT.

@param jwt

An optional specific JWT you wish to verify, not the one you can obtain from {@link #getSession}.

@param options

Various additional options that allow you to customize the behavior of this method.

@example

Get JWT claims, header and signature

const { data, error } = await supabase.auth.getClaims()
@example
§
getSession(): Promise<{
data: {
session: Session;
}
;
error: null;
}
| {
data: {
session: null;
}
;
error: AuthError;
}
| {
data: {
session: null;
}
;
error: null;
}
>
[src]

Returns the session, refreshing it if necessary.

The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out.

IMPORTANT: This method loads values directly from the storage attached to the client. If that storage is based on request cookies for example, the values in it may not be authentic and therefore it's strongly advised against using this method and its results in such circumstances. A warning will be emitted if this is detected. Use {@link #getUser()} instead.

@example

Get the session data

const { data, error } = await supabase.auth.getSession()
@example
§
getUser(jwt?: string): Promise<UserResponse>
[src]

Gets the current user details if there is an existing session. This method performs a network request to the Supabase Auth server, so the returned value is authentic and can be used to base authorization rules on.

@param jwt

Takes in an optional access token JWT. If no JWT is provided, the JWT from the current session is used.

@example

Get the logged in user with the current existing session

const { data: { user } } = await supabase.auth.getUser()
@example
@example

Get the logged in user with a custom access token jwt

const { data: { user } } = await supabase.auth.getUser(jwt)
§
getUserIdentities(): Promise<{
data: {
identities: UserIdentity[];
}
;
error: null;
}
| {
data: null;
error: AuthError;
}
>
[src]

Gets all the identities linked to a user.

@example

Returns a list of identities linked to the user

const { data, error } = await supabase.auth.getUserIdentities()
@example
§
initialize(): Promise<InitializeResult>
[src]

Initialize the auth client by loading the session from storage or detecting it from the URL after an OAuth, magic-link, or password-recovery redirect.

Most callers do not need to invoke this directly. The client calls it automatically during construction, and to react to sign-in events (including post-redirect events) you should subscribe to onAuthStateChange rather than awaiting initialize().

You only need to call it manually when you have opted out of the automatic call by passing skipAutoInitialize: true — for example, in an SSR context where you need to control initialization timing. In that case, awaiting initialize() returns the resolved session result (or any error encountered while detecting it from the URL).

§
isThrowOnErrorEnabled(): boolean
[src]

Returns whether error throwing mode is enabled for this client.

§
linkIdentity(credentials: SignInWithOAuthCredentials): Promise<OAuthResponse>
[src]

Links an oauth identity to an existing user. This method supports the PKCE flow.

linkIdentity(credentials: SignInWithIdTokenCredentials): Promise<AuthTokenResponse>
[src]

Links an OIDC identity to an existing user.

§
onAuthStateChange(callback: (event: AuthChangeEvent, session: Session | null) => void): {
data: {
subscription: Subscription;
}
;
}
[src]

Receive a notification every time an auth event happens. Safe to use without an async function as callback.

@param callback

A callback function to be invoked when an auth event happens.

onAuthStateChange(callback: (event: AuthChangeEvent, session: Session | null) => Promise<void>): {
data: {
subscription: Subscription;
}
;
}
deprecated
[src]

Receive a notification every time an auth event happens. Common reentry patterns (getUser, setSession, reading the session from inside a handler) complete normally. One hazard remains: calling refreshSession (or anything that routes through _callRefreshToken) from inside a TOKEN_REFRESHED handler. refreshingDeferred resolves only after _notifyAllSubscribers returns, so the inner refresh dedupes onto the outer's unresolved promise and the two wait on each other.

@param callback

A callback function to be invoked when an auth event happens.

@deprecated

Async callbacks can deadlock when they trigger a nested refresh from a TOKEN_REFRESHED event. Prefer the sync overload, or move refresh-triggering work outside the callback.

§
reauthenticate(): Promise<AuthResponse>
[src]

Sends a reauthentication OTP to the user's email or phone number. Requires the user to be signed-in.

@example
@example

Send reauthentication nonce

const { error } = await supabase.auth.reauthenticate()
§
refreshSession(currentSession?: {
refresh_token: string;
}
): Promise<AuthResponse>
[src]

Returns a new session, regardless of expiry status. Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession(). If the current session's refresh token is invalid, an error will be thrown.

@param currentSession

The current session. If passed in, it must contain a refresh token.

@example

Refresh session using the current session

const { data, error } = await supabase.auth.refreshSession()
const { session, user } = data
@example
@example

Refresh session using a refresh token

const { data, error } = await supabase.auth.refreshSession({ refresh_token })
const { session, user } = data
§

Register a passkey for the current authenticated user. Handles the full WebAuthn ceremony:

  1. Fetches registration challenge from server
  2. Prompts user via navigator.credentials.create()
  3. Verifies credential with server

Requires an active session. Requires auth.experimental.passkey: true.

§
resend(credentials: ResendParams): Promise<AuthOtpResponse>
[src]

Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP.

@example
@example

Resend an email signup confirmation

const { error } = await supabase.auth.resend({
  type: 'signup',
  email: 'email@example.com',
  options: {
    emailRedirectTo: 'https://example.com/welcome'
  }
})
@example
@example

Resend a phone signup confirmation

const { error } = await supabase.auth.resend({
  type: 'sms',
  phone: '1234567890'
})
@example
@example

Resend email change email

const { error } = await supabase.auth.resend({
  type: 'email_change',
  email: 'email@example.com'
})
@example
@example

Resend phone change OTP

const { error } = await supabase.auth.resend({
  type: 'phone_change',
  phone: '1234567890'
})
§
resetPasswordForEmail(email: string, options?: {
redirectTo?: string;
captchaToken?: string;
}
): Promise<{
data: {};
error: null;
}
| {
data: null;
error: AuthError;
}
>
[src]

Sends a password reset request to an email address. This method supports the PKCE flow.

@param email

The email address of the user.

@param options.redirectTo

The URL to send the user to after they click the password reset link.

@param options.captchaToken

Verification token received when the user completes the captcha on the site.

@example

Reset password

const { data, error } = await supabase.auth.resetPasswordForEmail(email, {
  redirectTo: 'https://example.com/update-password',
})
@example
@example

Reset password (React)

/**
 * Step 1: Send the user an email to get a password reset token.
 * This email contains a link which sends the user back to your application.
 *\/
const { data, error } = await supabase.auth
  .resetPasswordForEmail('user@email.com')

/**
 * Step 2: Once the user is redirected back to your application,
 * ask the user to reset their password.
 *\/
 useEffect(() => {
   supabase.auth.onAuthStateChange(async (event, session) => {
     if (event == "PASSWORD_RECOVERY") {
       const newPassword = prompt("What would you like your new password to be?");
       const { data, error } = await supabase.auth
         .updateUser({ password: newPassword })

       if (data) alert("Password updated successfully!")
       if (error) alert("There was an error updating your password.")
     }
   })
 }, [])
§
setSession(currentSession: {
access_token: string;
refresh_token: string;
}
): Promise<AuthResponse>
[src]

Sets the session data from the current session. If the current session is expired, setSession will take care of refreshing it to obtain a new session. If the refresh token or access token in the current session is invalid, an error will be thrown.

@param currentSession

The current session that minimally contains an access token and refresh token.

@example
@example

Set the session

  const { data, error } = await supabase.auth.setSession({
    access_token,
    refresh_token
  })
@example
§
signInAnonymously(credentials?: SignInAnonymouslyCredentials): Promise<AuthResponse>
[src]

Creates a new anonymous user.

@return

A session where the is_anonymous claim in the access token JWT set to true

@example

Create an anonymous user

const { data, error } = await supabase.auth.signInAnonymously({
  options: {
    captchaToken
  }
});
@example
@example

Create an anonymous user with custom user metadata

const { data, error } = await supabase.auth.signInAnonymously({
  options: {
    data
  }
})
§
signInWithIdToken(credentials: SignInWithIdTokenCredentials): Promise<AuthTokenResponse>
[src]

Allows signing in with an OIDC ID token. The authentication provider used should be enabled and configured.

@example

Sign In using ID Token

const { data, error } = await supabase.auth.signInWithIdToken({
  provider: 'google',
  token: 'your-id-token'
})
@example
§
signInWithOAuth(credentials: SignInWithOAuthCredentials): Promise<OAuthResponse>
[src]

Log in an existing user via a third-party provider. This method supports the PKCE flow.

@example

Sign in using a third-party provider

const { data, error } = await supabase.auth.signInWithOAuth({
  provider: 'github'
})
@example
@example
@example

Sign in using a third-party provider with redirect

const { data, error } = await supabase.auth.signInWithOAuth({
  provider: 'github',
  options: {
    redirectTo: 'https://example.com/welcome'
  }
})
@example
@example

Sign in with scopes and access provider tokens

// Register this immediately after calling createClient!
// Because signInWithOAuth causes a redirect, you need to fetch the
// provider tokens from the callback.
supabase.auth.onAuthStateChange((event, session) => {
  if (session && session.provider_token) {
    window.localStorage.setItem('oauth_provider_token', session.provider_token)
  }

  if (session && session.provider_refresh_token) {
    window.localStorage.setItem('oauth_provider_refresh_token', session.provider_refresh_token)
  }

  if (event === 'SIGNED_OUT') {
    window.localStorage.removeItem('oauth_provider_token')
    window.localStorage.removeItem('oauth_provider_refresh_token')
  }
})

// Call this on your Sign in with GitHub button to initiate OAuth
// with GitHub with the requested elevated scopes.
await supabase.auth.signInWithOAuth({
  provider: 'github',
  options: {
    scopes: 'repo gist notifications'
  }
})
§
signInWithOtp(credentials: SignInWithPasswordlessCredentials): Promise<AuthOtpResponse>
[src]

Log in a user using magiclink or a one-time password (OTP).

If the {{ .ConfirmationURL }} variable is specified in the email template, a magiclink will be sent. If the {{ .Token }} variable is specified in the email template, an OTP will be sent. If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins.

Be aware that you may get back an error message that will not distinguish between the cases where the account does not exist or, that the account can only be accessed via social login.

Do note that you will need to configure a Whatsapp sender on Twilio if you are using phone sign in with the 'whatsapp' channel. The whatsapp channel is not supported on other providers at this time. This method supports PKCE when an email is passed.

@example
@example

Sign in with email

const { data, error } = await supabase.auth.signInWithOtp({
  email: 'example@email.com',
  options: {
    emailRedirectTo: 'https://example.com/welcome'
  }
})
@example
@example
@example

Sign in with SMS OTP

const { data, error } = await supabase.auth.signInWithOtp({
  phone: '+13334445555',
})
@example
@example

Sign in with WhatsApp OTP

const { data, error } = await supabase.auth.signInWithOtp({
  phone: '+13334445555',
  options: {
    channel:'whatsapp',
  }
})
§

Sign in with a passkey. Handles the full WebAuthn ceremony:

  1. Fetches authentication challenge from server
  2. Prompts user via navigator.credentials.get()
  3. Verifies credential with server and creates session

Requires auth.experimental.passkey: true.

§
signInWithPassword(credentials: SignInWithPasswordCredentials): Promise<AuthTokenResponsePassword>
[src]

Log in an existing user with an email and password or phone and password.

Be aware that you may get back an error message that will not distinguish between the cases where the account does not exist or that the email/phone and password combination is wrong or that the account can only be accessed via social login.

@example

Sign in with email and password

const { data, error } = await supabase.auth.signInWithPassword({
  email: 'example@email.com',
  password: 'example-password',
})
@example
@example

Sign in with phone and password

const { data, error } = await supabase.auth.signInWithPassword({
  phone: '+13334445555',
  password: 'some-password',
})
@example
@example

Handling errors

const { data, error } = await supabase.auth.signInWithPassword({
  email: 'example@email.com',
  password: 'example-password',
})
if (error) {
  console.error(error)
  return
}
§
signInWithSSO(params: SignInWithSSO): Promise<SSOResponse>
[src]

Attempts a single-sign on using an enterprise Identity Provider. A successful SSO attempt will redirect the current page to the identity provider authorization page. The redirect URL is implementation and SSO protocol specific.

You can use it by providing a SSO domain. Typically you can extract this domain by asking users for their email address. If this domain is registered on the Auth instance the redirect will use that organization's currently active SSO Identity Provider for the login.

If you have built an organization-specific login page, you can use the organization's SSO Identity Provider UUID directly instead.

@example

Sign in with email domain

  // You can extract the user's email domain and use it to trigger the
  // authentication flow with the correct identity provider.

  const { data, error } = await supabase.auth.signInWithSSO({
    domain: 'company.com'
  })

  if (data?.url) {
    // redirect the user to the identity provider's authentication flow
    window.location.href = data.url
  }
@example

Sign in with provider UUID

  // Useful when you need to map a user's sign in request according
  // to different rules that can't use email domains.

  const { data, error } = await supabase.auth.signInWithSSO({
    providerId: '21648a9d-8d5a-4555-a9d1-d6375dc14e92'
  })

  if (data?.url) {
    // redirect the user to the identity provider's authentication flow
    window.location.href = data.url
  }
§
signInWithWeb3(credentials: Web3Credentials): Promise<{
data: {
session: Session;
user: User;
}
;
error: null;
}
| {
data: {
session: null;
user: null;
}
;
error: AuthError;
}
>
[src]

Signs in a user by verifying a message signed by the user's private key. Supports Ethereum (via Sign-In-With-Ethereum) & Solana (Sign-In-With-Solana) standards, both of which derive from the EIP-4361 standard With slight variation on Solana's side.

@example

Sign in with Solana or Ethereum (Window API)

  // uses window.ethereum for the wallet
  const { data, error } = await supabase.auth.signInWithWeb3({
    chain: 'ethereum',
    statement: 'I accept the Terms of Service at https://example.com/tos'
  })

  // uses window.solana for the wallet
  const { data, error } = await supabase.auth.signInWithWeb3({
    chain: 'solana',
    statement: 'I accept the Terms of Service at https://example.com/tos'
  })
@example

Sign in with Ethereum (Message and Signature)

  const { data, error } = await supabase.auth.signInWithWeb3({
    chain: 'ethereum',
    message: '<sign in with ethereum message>',
    signature: '<hex of the ethereum signature over the message>',
  })
@example

Sign in with Solana (Brave)

  const { data, error } = await supabase.auth.signInWithWeb3({
    chain: 'solana',
    statement: 'I accept the Terms of Service at https://example.com/tos',
    wallet: window.braveSolana
  })
@example

Sign in with Solana (Wallet Adapter)

  function SignInButton() {
  const wallet = useWallet()

  return (
    <>
      {wallet.connected ? (
        <button
          onClick={() => {
            supabase.auth.signInWithWeb3({
              chain: 'solana',
              statement: 'I accept the Terms of Service at https://example.com/tos',
              wallet,
            })
          }}
        >
          Sign in with Solana
        </button>
      ) : (
        <WalletMultiButton />
      )}
    </>
  )
}

function App() {
  const endpoint = clusterApiUrl('devnet')
  const wallets = useMemo(() => [], [])

  return (
    <ConnectionProvider endpoint={endpoint}>
      <WalletProvider wallets={wallets}>
        <WalletModalProvider>
          <SignInButton />
        </WalletModalProvider>
      </WalletProvider>
    </ConnectionProvider>
  )
}
§
signOut(options?: SignOut): Promise<{
error: AuthError | null;
}
>
[src]

Inside a browser context, signOut() will remove the logged in user from the browser session and log them out - removing all items from localstorage and then trigger a "SIGNED_OUT" event.

For server-side management, you can revoke all refresh tokens for a user by passing a user's JWT through to auth.api.signOut(JWT: string). There is no way to revoke a user's access token jwt until it expires. It is recommended to set a shorter expiry on the jwt for this reason.

If using others scope, no SIGNED_OUT event is fired!

Warning: the default scope is 'global'. This signs the user out of every device they are currently signed in on, not just the current tab/session. If you only want to sign the user out of the current session (the behavior most other auth libraries default to), pass { scope: 'local' } explicitly.

@example

Sign out of every device (global – default)

const { error } = await supabase.auth.signOut()
@example

Sign out only the current session (recommended for most apps)

const { error } = await supabase.auth.signOut({ scope: 'local' })
@example

Sign out of all other sessions, keep the current one

const { error } = await supabase.auth.signOut({ scope: 'others' })
§
signUp(credentials: SignUpWithPasswordCredentials): Promise<AuthResponse>
[src]

Creates a new user.

Be aware that if a user account exists in the system you may get back an error message that attempts to hide this information from the user. This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled.

@return

A logged-in session if the server has "autoconfirm" ON

@return

A user if the server has "autoconfirm" OFF

@example

Sign up with an email and password

const { data, error } = await supabase.auth.signUp({
  email: 'example@email.com',
  password: 'example-password',
})
@example
@example

Sign up with a phone number and password (SMS)

const { data, error } = await supabase.auth.signUp({
  phone: '123456789',
  password: 'example-password',
  options: {
    channel: 'sms'
  }
})
@example
@example

Sign up with a phone number and password (whatsapp)

const { data, error } = await supabase.auth.signUp({
  phone: '123456789',
  password: 'example-password',
  options: {
    channel: 'whatsapp'
  }
})
@example

Sign up with additional user metadata

const { data, error } = await supabase.auth.signUp(
  {
    email: 'example@email.com',
    password: 'example-password',
    options: {
      data: {
        first_name: 'John',
        age: 27,
      }
    }
  }
)
@example
@example

Sign up with a redirect URL

const { data, error } = await supabase.auth.signUp(
  {
    email: 'example@email.com',
    password: 'example-password',
    options: {
      emailRedirectTo: 'https://example.com/welcome'
    }
  }
)
§
startAutoRefresh(): Promise<void>
[src]

Starts an auto-refresh process in the background. The session is checked every few seconds. Close to the time of expiration a process is started to refresh the session. If refreshing fails it will be retried for as long as necessary.

If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need to call this function, it will be called for you.

On browsers the refresh process works only when the tab/window is in the foreground to conserve resources as well as prevent race conditions and flooding auth with requests. If you call this method any managed visibility change callback will be removed and you must manage visibility changes on your own.

On non-browser platforms the refresh process works continuously in the background, which may not be desirable. You should hook into your platform's foreground indication mechanism and call these methods appropriately to conserve resources.

{@see #stopAutoRefresh}

@example

Start and stop auto refresh in React Native

import { AppState } from 'react-native'

// make sure you register this only once!
AppState.addEventListener('change', (state) => {
  if (state === 'active') {
    supabase.auth.startAutoRefresh()
  } else {
    supabase.auth.stopAutoRefresh()
  }
})
§
stopAutoRefresh(): Promise<void>
[src]

Stops an active auto refresh process running in the background (if any).

If you call this method any managed visibility change callback will be removed and you must manage visibility changes on your own.

See {@link #startAutoRefresh} for more details.

@example

Start and stop auto refresh in React Native

import { AppState } from 'react-native'

// make sure you register this only once!
AppState.addEventListener('change', (state) => {
  if (state === 'active') {
    supabase.auth.startAutoRefresh()
  } else {
    supabase.auth.stopAutoRefresh()
  }
})
§
unlinkIdentity(identity: UserIdentity): Promise<{
data: {};
error: null;
}
| {
data: null;
error: AuthError;
}
>
[src]

Unlinks an identity from a user by deleting it. The user will no longer be able to sign in with that identity once it's unlinked.

@example

Unlink an identity

// retrieve all identities linked to a user
const identities = await supabase.auth.getUserIdentities()

// find the google identity
const googleIdentity = identities.find(
  identity => identity.provider === 'google'
)

// unlink the google identity
const { error } = await supabase.auth.unlinkIdentity(googleIdentity)
§
updateUser(attributes: UserAttributes, options?: {
emailRedirectTo?: string | undefined;
}
): Promise<UserResponse>
[src]

Updates user data for a logged in user.

@example
@example

Update the email for an authenticated user

const { data, error } = await supabase.auth.updateUser({
  email: 'new@email.com'
})
@example
@example
@example

Update the phone number for an authenticated user

const { data, error } = await supabase.auth.updateUser({
  phone: '123456789'
})
@example

Update the password for an authenticated user

const { data, error } = await supabase.auth.updateUser({
  password: 'new password'
})
@example
@example

Update the user's metadata

const { data, error } = await supabase.auth.updateUser({
  data: { hello: 'world' }
})
@example
@example

Update the user's password with a nonce

const { data, error } = await supabase.auth.updateUser({
  password: 'new password',
  nonce: '123456'
})
§
verifyOtp(params: VerifyOtpParams): Promise<AuthResponse>
[src]

Log in a user given a User supplied OTP or TokenHash received through mobile or email.

@example

Verify Signup One-Time Password (OTP)

const { data, error } = await supabase.auth.verifyOtp({ email, token, type: 'email'})
@example
@example

Verify SMS One-Time Password (OTP)

const { data, error } = await supabase.auth.verifyOtp({ phone, token, type: 'sms'})
@example

Verify Email Auth (Token Hash)

const { data, error } = await supabase.auth.verifyOtp({ token_hash: tokenHash, type: 'email'})

§Static Properties

§
nextInstanceID
[src]