@supabase/gotrue-js
Version:
Official SDK for Supabase Auth
1,406 lines (1,332 loc) • 249 kB
text/typescript
import GoTrueAdminApi from './GoTrueAdminApi'
import {
AUTO_REFRESH_TICK_DURATION_MS,
AUTO_REFRESH_TICK_THRESHOLD,
DEFAULT_HEADERS,
EXPIRY_MARGIN_MS,
GOTRUE_URL,
JWKS_TTL,
PKCE_FLOW_ID_PARAM,
REFRESH_FAILURE_COOLDOWN_MS,
STORAGE_KEY,
} from './lib/constants'
import {
AuthError,
AuthImplicitGrantRedirectError,
AuthInvalidCredentialsError,
AuthInvalidJwtError,
AuthInvalidTokenResponseError,
AuthPKCECodeVerifierMissingError,
AuthPKCEGrantCodeExchangeError,
AuthRefreshDiscardedError,
AuthSessionMissingError,
AuthUnknownError,
isAuthApiError,
isAuthError,
isAuthImplicitGrantRedirectError,
isAuthRefreshDiscardedError,
isAuthRetryableFetchError,
isAuthSessionMissingError,
} from './lib/errors'
import {
Fetch,
_request,
_sessionResponse,
_sessionResponsePassword,
_ssoResponse,
_userResponse,
} from './lib/fetch'
import {
appendFlowIdToRedirectTo,
assertPasskeyExperimentalEnabled,
decodeJWT,
deepClone,
Deferred,
generateCallbackId,
getAlgorithm,
getCodeChallengeAndMethod,
getItemAsync,
insecureUserWarningProxy,
isBrowser,
parseParametersFromURL,
pkceVerifierSlotKey,
removeAllPKCEVerifiers,
removeItemAsync,
removePKCEVerifier,
resolveFetch,
retrievePKCEVerifier,
retryable,
setItemAsync,
sleep,
supportsLocalStorage,
userNotAvailableProxy,
validateExp,
validatePKCEFlowId,
} from './lib/helpers'
import { memoryLocalStorageAdapter } from './lib/local-storage'
import { LockAcquireTimeoutError, navigatorLock } from './lib/locks'
import { polyfillGlobalThis } from './lib/polyfills'
import { version } from './lib/version'
import { bytesToBase64URL, stringToUint8Array } from './lib/base64url'
import type {
AuthChangeEvent,
AuthenticatorAssuranceLevels,
AuthFlowType,
AuthMFAChallengePhoneResponse,
AuthMFAChallengeResponse,
AuthMFAChallengeTOTPResponse,
AuthMFAChallengeWebauthnResponse,
AuthMFAChallengeWebauthnServerResponse,
AuthMFAEnrollPhoneResponse,
AuthMFAEnrollResponse,
AuthMFAEnrollTOTPResponse,
AuthMFAEnrollWebauthnResponse,
AuthMFAGetAuthenticatorAssuranceLevelResponse,
AuthMFAListFactorsResponse,
AuthMFAUnenrollResponse,
AuthMFAVerifyResponse,
AuthOtpResponse,
AuthResponse,
AuthResponsePassword,
AuthTokenResponse,
AuthTokenResponsePassword,
CallRefreshTokenResult,
EthereumWallet,
EthereumWeb3Credentials,
Factor,
GoTrueClientOptions,
GoTrueMFAApi,
InitializeResult,
JWK,
JwtHeader,
JwtPayload,
LockFunc,
MFAChallengeAndVerifyParams,
MFAChallengeParams,
MFAChallengePhoneParams,
MFAChallengeTOTPParams,
MFAChallengeWebauthnParams,
MFAEnrollParams,
MFAEnrollPhoneParams,
MFAEnrollTOTPParams,
MFAEnrollWebauthnParams,
MFAUnenrollParams,
MFAVerifyParams,
MFAVerifyPhoneParams,
MFAVerifyTOTPParams,
MFAVerifyWebauthnParamFields,
MFAVerifyWebauthnParams,
OAuthResponse,
AuthOAuthServerApi,
AuthOAuthAuthorizationDetailsResponse,
AuthOAuthConsentResponse,
AuthOAuthGrantsResponse,
AuthOAuthRevokeGrantResponse,
Prettify,
Provider,
ResendParams,
Session,
SignInAnonymouslyCredentials,
SignInWithIdTokenCredentials,
SignInWithOAuthCredentials,
SignInWithPasswordCredentials,
SignInWithPasswordlessCredentials,
SignInWithSSO,
SignOut,
SignUpWithPasswordCredentials,
SolanaWallet,
SolanaWeb3Credentials,
SSOResponse,
StrictOmit,
Subscription,
SupportedStorage,
User,
UserAttributes,
UserIdentity,
UserResponse,
VerifyOtpParams,
Web3Credentials,
AuthPasskeyApi,
ExperimentalFeatureFlags,
SignInWithPasskeyCredentials,
RegisterPasskeyCredentials,
VerifyPasskeyRegistrationParams,
StartPasskeyAuthenticationParams,
VerifyPasskeyAuthenticationParams,
PasskeyUpdateParams,
PasskeyDeleteParams,
AuthPasskeyRegistrationOptionsResponse,
AuthPasskeyRegistrationVerifyResponse,
AuthPasskeyAuthenticationOptionsResponse,
AuthPasskeyAuthenticationVerifyResponse,
AuthPasskeyListResponse,
AuthPasskeyUpdateResponse,
AuthPasskeyDeleteResponse,
} from './lib/types'
import {
createSiweMessage,
fromHex,
getAddress,
Hex,
SiweMessage,
toHex,
} from './lib/web3/ethereum'
import {
createCredential,
deserializeCredentialCreationOptions,
deserializeCredentialRequestOptions,
getCredential,
serializeCredentialCreationResponse,
serializeCredentialRequestResponse,
browserSupportsWebAuthn,
webAuthnAbortService,
WebAuthnApi,
} from './lib/webauthn'
import {
AuthenticationCredential,
PublicKeyCredentialJSON,
RegistrationCredential,
} from './lib/webauthn.dom'
polyfillGlobalThis() // Make "globalThis" available
const DEFAULT_OPTIONS: Omit<
Required<GoTrueClientOptions>,
'fetch' | 'storage' | 'userStorage' | 'lock'
> = {
url: GOTRUE_URL,
storageKey: STORAGE_KEY,
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: true,
headers: DEFAULT_HEADERS,
flowType: 'implicit',
debug: false,
hasCustomAuthorizationHeader: false,
throwOnError: false,
lockAcquireTimeout: 5000, // 5 seconds. Only used when a custom `lock` is supplied. TODO(v3): remove.
skipAutoInitialize: false,
experimental: {},
}
/**
* No-op lock used internally as a placeholder. Kept so older test setups that
* inject this exact reference do not break; new code never sees it because
* `this.lock` stays `null` when no custom lock is supplied (lockless path).
* TODO(v3): remove with the legacy lock path.
*/
async function lockNoOp<R>(name: string, acquireTimeout: number, fn: () => Promise<R>): Promise<R> {
return await fn()
}
/**
* Caches JWKS values for all clients created in the same environment. This is
* especially useful for shared-memory execution environments such as Vercel's
* Fluid Compute, AWS Lambda or Supabase's Edge Functions. Regardless of how
* many clients are created, if they share the same storage key they will use
* the same JWKS cache, significantly speeding up getClaims() with asymmetric
* JWTs.
*/
const GLOBAL_JWKS: { [storageKey: string]: { cachedAt: number; jwks: { keys: JWK[] } } } = {}
export default class GoTrueClient {
private static nextInstanceID: Record<string, number> = {}
private instanceID: number
/**
* Namespace for the GoTrue admin methods.
* These methods should only be used in a trusted server-side environment.
*/
admin: GoTrueAdminApi
/**
* Namespace for the MFA methods.
*/
mfa: GoTrueMFAApi
/**
* 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.
*/
oauth: AuthOAuthServerApi
/**
* Namespace for passkey methods.
* Includes lower-level two-step registration/authentication and passkey management.
*
* Requires `auth.experimental.passkey: true`; otherwise all methods throw.
*/
passkey: AuthPasskeyApi
/**
* The storage key used to identify the values saved in localStorage
*/
protected storageKey: string
protected flowType: AuthFlowType
/**
* The JWKS used for verifying asymmetric JWTs
*/
protected get jwks() {
return GLOBAL_JWKS[this.storageKey]?.jwks ?? { keys: [] }
}
protected set jwks(value: { keys: JWK[] }) {
GLOBAL_JWKS[this.storageKey] = { ...GLOBAL_JWKS[this.storageKey], jwks: value }
}
protected get jwks_cached_at() {
return GLOBAL_JWKS[this.storageKey]?.cachedAt ?? Number.MIN_SAFE_INTEGER
}
protected set jwks_cached_at(value: number) {
GLOBAL_JWKS[this.storageKey] = { ...GLOBAL_JWKS[this.storageKey], cachedAt: value }
}
protected autoRefreshToken: boolean
protected persistSession: boolean
protected storage: SupportedStorage
/**
* @experimental
*/
protected userStorage: SupportedStorage | null = null
protected memoryStorage: { [key: string]: string } | null = null
protected stateChangeEmitters: Map<string | symbol, Subscription> = new Map()
protected autoRefreshTicker: ReturnType<typeof setInterval> | null = null
protected autoRefreshTickTimeout: ReturnType<typeof setTimeout> | null = null
protected visibilityChangedCallback: (() => Promise<any>) | null = null
protected refreshingDeferred: Deferred<CallRefreshTokenResult> | null = null
/**
* Cache of the most recent refresh failure, keyed by the refresh token
* that failed. Serial callers passing the *same* token within
* `REFRESH_FAILURE_COOLDOWN_MS` (including subsequent auto-refresh ticks)
* receive this cached result instead of firing another `/token` request.
* Callers passing a *different* token (token rotation pickup, explicit
* `setSession`/`refreshSession({ refresh_token })`, multi-account switch)
* bypass the cache and attempt a fresh refresh as they should.
* Cleared on any successful refresh (locally or via BroadcastChannel from
* another tab) and on `_removeSession`.
*
* Pairs with `refreshingDeferred`: concurrent callers share the in-flight
* promise, serial callers within the cooldown share the failure result.
*/
protected lastRefreshFailure: {
refreshToken: string
result: CallRefreshTokenResult
expiresAt: number
} | null = null
/**
* 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).
*/
protected _sessionRemovalEpoch = 0
/**
* 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
*/
protected initializePromise: Promise<InitializeResult> | null = null
/**
* Non-null only while `initialize()` is running. While open,
* `_notifyAllSubscribers` enqueues init-chain notifications (those fired with
* `broadcast = true`, i.e. from `_recoverAndRefresh`) into this array instead
* of firing directly, so that `initializePromise` is guaranteed to be
* resolved before any subscriber callback runs. Callbacks that call
* `getSession()` / `getUser()` etc. would otherwise deadlock because those
* methods await `initializePromise`. Notifications from the incoming
* BroadcastChannel handler (`broadcast = false`) are not enqueued — they fire
* immediately. Flushed (in order) by `initialize()` after `initializePromise`
* settles.
*/
private _pendingInitNotifications: Array<{
event: AuthChangeEvent
session: Session | null
broadcast: boolean
}> | null = null
protected detectSessionInUrl:
| boolean
| ((url: URL, params: { [parameter: string]: string }) => boolean) = true
protected url: string
protected headers: {
[key: string]: string
}
protected hasCustomAuthorizationHeader = false
protected suppressGetSessionWarning = false
protected fetch: Fetch
/**
* 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.
*/
protected lock: LockFunc | null = null
protected lockAcquired = false
protected pendingInLock: Promise<any>[] = []
protected throwOnError: boolean
/**
* Only consulted when a custom `lock` is supplied. TODO(v3): remove.
*/
protected lockAcquireTimeout: number
/**
* Opt-in flags for experimental features. Defaults to an empty object.
* See `GoTrueClientOptions.experimental`.
*/
protected experimental: ExperimentalFeatureFlags
/**
* Used to broadcast state change events to other tabs listening.
*/
protected broadcastChannel: BroadcastChannel | null = null
protected logDebugMessages: boolean
protected logger: (message: string, ...args: any[]) => void = console.log
/**
* Create a new client for use in the browser.
*
* @example Using supabase-js (recommended)
* ```ts
* 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
* ```ts
* 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',
* })
* ```
*/
constructor(options: GoTrueClientOptions) {
const settings = { ...DEFAULT_OPTIONS, ...options }
this.storageKey = settings.storageKey
this.instanceID = GoTrueClient.nextInstanceID[this.storageKey] ?? 0
GoTrueClient.nextInstanceID[this.storageKey] = this.instanceID + 1
this.logDebugMessages = !!settings.debug
if (typeof settings.debug === 'function') {
this.logger = settings.debug
}
if (this.instanceID > 0 && isBrowser()) {
const message = `${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`
console.warn(message)
if (this.logDebugMessages) {
console.trace(message)
}
}
this.persistSession = settings.persistSession
this.autoRefreshToken = settings.autoRefreshToken
this.experimental = settings.experimental ?? {}
this.admin = new GoTrueAdminApi({
url: settings.url,
headers: settings.headers,
fetch: settings.fetch,
experimental: this.experimental,
})
this.url = settings.url
this.headers = settings.headers
this.fetch = resolveFetch(settings.fetch)
this.detectSessionInUrl = settings.detectSessionInUrl
this.flowType = settings.flowType
this.hasCustomAuthorizationHeader = settings.hasCustomAuthorizationHeader
this.throwOnError = settings.throwOnError
// Always wire `lockAcquireTimeout` even on the lockless path: consumers
// (including supabase-js tests) read it off the client to verify option
// flow-through.
this.lockAcquireTimeout = settings.lockAcquireTimeout
// TODO(v3): remove. Legacy opt-in path preserved for backwards
// compatibility with callers passing a custom `lock` (typically React
// Native `processLock` or Node multi-process setups). When `settings.lock`
// is null the client uses its lockless coordination — no `navigator.locks`
// by default, no implicit `processLock`.
if (settings.lock != null) {
this.lock = settings.lock
}
if (!this.jwks) {
this.jwks = { keys: [] }
this.jwks_cached_at = Number.MIN_SAFE_INTEGER
}
this.mfa = {
verify: this._verify.bind(this),
enroll: this._enroll.bind(this),
unenroll: this._unenroll.bind(this),
challenge: this._challenge.bind(this),
listFactors: this._listFactors.bind(this),
challengeAndVerify: this._challengeAndVerify.bind(this),
getAuthenticatorAssuranceLevel: this._getAuthenticatorAssuranceLevel.bind(this),
webauthn: new WebAuthnApi(this),
}
this.oauth = {
getAuthorizationDetails: this._getAuthorizationDetails.bind(this),
approveAuthorization: this._approveAuthorization.bind(this),
denyAuthorization: this._denyAuthorization.bind(this),
listGrants: this._listOAuthGrants.bind(this),
revokeGrant: this._revokeOAuthGrant.bind(this),
}
this.passkey = {
startRegistration: this._startPasskeyRegistration.bind(this),
verifyRegistration: this._verifyPasskeyRegistration.bind(this),
startAuthentication: this._startPasskeyAuthentication.bind(this),
verifyAuthentication: this._verifyPasskeyAuthentication.bind(this),
list: this._listPasskeys.bind(this),
update: this._updatePasskey.bind(this),
delete: this._deletePasskey.bind(this),
}
if (this.persistSession) {
if (settings.storage) {
this.storage = settings.storage
} else {
if (supportsLocalStorage()) {
this.storage = globalThis.localStorage
} else {
this.memoryStorage = {}
this.storage = memoryLocalStorageAdapter(this.memoryStorage)
}
}
if (settings.userStorage) {
this.userStorage = settings.userStorage
}
} else {
this.memoryStorage = {}
this.storage = memoryLocalStorageAdapter(this.memoryStorage)
}
if (isBrowser() && globalThis.BroadcastChannel && this.persistSession && this.storageKey) {
try {
this.broadcastChannel = new globalThis.BroadcastChannel(this.storageKey)
} catch (e) {
console.error(
'Failed to create a new BroadcastChannel, multi-tab state changes will not be available',
e
)
}
this.broadcastChannel?.addEventListener('message', async (event) => {
this._debug('received broadcast notification from other tab or client', event)
// Another tab successfully refreshed or signed in — any cached
// failure in this tab is stale and should not block the next
// refresh attempt.
if (event.data.event === 'TOKEN_REFRESHED' || event.data.event === 'SIGNED_IN') {
this.lastRefreshFailure = null
}
try {
await this._notifyAllSubscribers(event.data.event, event.data.session, false) // broadcast = false so we don't get an endless loop of messages
} catch (error) {
this._debug('#broadcastChannel', 'error', error)
}
})
}
// Only auto-initialize if not explicitly disabled. Skipped in SSR contexts
// where initialization timing must be controlled. All public methods have
// lazy initialization, so the client remains fully functional.
if (!settings.skipAutoInitialize) {
this.initialize().catch((error) => {
this._debug('#initialize()', 'error', error)
})
}
}
/**
* Returns whether error throwing mode is enabled for this client.
*/
public isThrowOnErrorEnabled(): boolean {
return this.throwOnError
}
/**
* 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.
*/
private _returnResult<T extends { error: any }>(result: T): T {
if (this.throwOnError && result && result.error) {
throw result.error
}
return result
}
private _logPrefix(): string {
return (
'GoTrueClient@' +
`${this.storageKey}:${this.instanceID} (${version}) ${new Date().toISOString()}`
)
}
private _debug(...args: any[]): GoTrueClient {
if (this.logDebugMessages) {
this.logger(this._logPrefix(), ...args)
}
return this
}
/**
* 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).
*
* @category Auth
*/
async initialize(): Promise<InitializeResult> {
if (this.initializePromise) {
return await this.initializePromise
}
// Open the notification queue before _initialize() runs so that every
// _notifyAllSubscribers call inside the init chain enqueues instead of
// firing. Without this, a callback receiving SIGNED_IN (or TOKEN_REFRESHED
// / SIGNED_OUT) during _recoverAndRefresh would deadlock if it called
// getSession() / getUser() — those methods await initializePromise, which
// can only resolve after the callback returns, which can only return after
// getSession() resolves. The queue is flushed below after initializePromise
// has settled, so callbacks run with a fully resolved initializePromise.
this._pendingInitNotifications = []
this.initializePromise = (async () => {
if (this.lock != null) {
// TODO(v3): remove legacy lock path
return await this._acquireLock(this.lockAcquireTimeout, async () => {
return await this._initialize()
})
}
return await this._initialize()
})()
const result = await this.initializePromise
// initializePromise is now resolved — flush queued notifications in order.
// Callbacks can safely call getSession() / getUser() / signOut() etc.
const queue = this._pendingInitNotifications ?? []
this._pendingInitNotifications = null
for (const n of queue) {
await this._notifyAllSubscribers(n.event, n.session, n.broadcast)
}
return result
}
/**
* 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
*/
private async _initialize(): Promise<InitializeResult> {
try {
let params: { [parameter: string]: string } = {}
let callbackUrlType = 'none'
if (isBrowser()) {
params = parseParametersFromURL(window.location.href)
if (this._isImplicitGrantCallback(params)) {
callbackUrlType = 'implicit'
} else if (await this._isPKCECallback(params)) {
callbackUrlType = 'pkce'
}
}
/**
* Attempt to get the session from the URL only if these conditions are fulfilled
*
* Note: If the URL isn't one of the callback url types (implicit or pkce),
* then there could be an existing session so we don't want to prematurely remove it
*/
if (isBrowser() && this.detectSessionInUrl && callbackUrlType !== 'none') {
const { data, error } = await this._getSessionFromURL(params, callbackUrlType)
if (error) {
this._debug('#_initialize()', 'error detecting session from URL', error)
if (isAuthImplicitGrantRedirectError(error)) {
const errorCode = error.details?.code
if (
errorCode === 'identity_already_exists' ||
errorCode === 'identity_not_found' ||
errorCode === 'single_identity_not_deletable'
) {
return { error }
}
}
// Don't remove existing session on URL login failure.
// A failed attempt (e.g. reused magic link) shouldn't invalidate a valid session.
return { error }
}
const { session, redirectType } = data
this._debug(
'#_initialize()',
'detected session in URL',
session,
'redirect type',
redirectType
)
await this._saveSession(session)
setTimeout(async () => {
if (redirectType === 'recovery') {
await this._notifyAllSubscribers('PASSWORD_RECOVERY', session)
} else {
await this._notifyAllSubscribers('SIGNED_IN', session)
}
}, 0)
return { error: null }
}
// no login attempt via callback url try to recover session from storage
await this._recoverAndRefresh()
return { error: null }
} catch (error) {
if (isAuthError(error)) {
return this._returnResult({ error })
}
return this._returnResult({
error: new AuthUnknownError('Unexpected error during initialization', error),
})
} finally {
await this._handleVisibilityChange()
this._debug('#_initialize()', 'end')
}
}
/**
* Creates a new anonymous user.
*
* @returns A session where the is_anonymous claim in the access token JWT set to true
*
* @category Auth
*
* @remarks
* - Returns an anonymous user
* - It is recommended to set up captcha for anonymous sign-ins to prevent abuse. You can pass in the captcha token in the `options` param.
*
* @example Create an anonymous user
* ```js
* const { data, error } = await supabase.auth.signInAnonymously({
* options: {
* captchaToken
* }
* });
* ```
*
* @exampleResponse Create an anonymous user
* ```json
* {
* "data": {
* "user": {
* "id": "11111111-1111-1111-1111-111111111111",
* "aud": "authenticated",
* "role": "authenticated",
* "email": "",
* "phone": "",
* "last_sign_in_at": "2024-01-01T00:00:00Z",
* "app_metadata": {},
* "user_metadata": {},
* "identities": [],
* "created_at": "2024-01-01T00:00:00Z",
* "updated_at": "2024-01-01T00:00:00Z",
* "is_anonymous": true
* },
* "session": {
* "access_token": "<ACCESS_TOKEN>",
* "token_type": "bearer",
* "expires_in": 3600,
* "expires_at": 1700000000,
* "refresh_token": "<REFRESH_TOKEN>",
* "user": {
* "id": "11111111-1111-1111-1111-111111111111",
* "aud": "authenticated",
* "role": "authenticated",
* "email": "",
* "phone": "",
* "last_sign_in_at": "2024-01-01T00:00:00Z",
* "app_metadata": {},
* "user_metadata": {},
* "identities": [],
* "created_at": "2024-01-01T00:00:00Z",
* "updated_at": "2024-01-01T00:00:00Z",
* "is_anonymous": true
* }
* }
* },
* "error": null
* }
* ```
*
* @example Create an anonymous user with custom user metadata
* ```js
* const { data, error } = await supabase.auth.signInAnonymously({
* options: {
* data
* }
* })
* ```
*/
async signInAnonymously(credentials?: SignInAnonymouslyCredentials): Promise<AuthResponse> {
try {
const res = await _request(this.fetch, 'POST', `${this.url}/signup`, {
headers: this.headers,
body: {
data: credentials?.options?.data ?? {},
gotrue_meta_security: { captcha_token: credentials?.options?.captchaToken },
},
xform: _sessionResponse,
})
const { data, error } = res
if (error || !data) {
return this._returnResult({ data: { user: null, session: null }, error: error })
}
const session: Session | null = data.session
const user: User | null = data.user
if (data.session) {
await this._saveSession(data.session)
await this._notifyAllSubscribers('SIGNED_IN', session)
}
return this._returnResult({ data: { user, session }, error: null })
} catch (error) {
if (isAuthError(error)) {
return this._returnResult({ data: { user: null, session: null }, error })
}
throw error
}
}
/**
* 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.
*
* @returns A logged-in session if the server has "autoconfirm" ON
* @returns A user if the server has "autoconfirm" OFF
*
* @category Auth
*
* @remarks
* - By default, the user needs to verify their email address before logging in. To turn this off, disable **Confirm email** in [your project](/dashboard/project/_/auth/providers).
* - **Confirm email** determines if users need to confirm their email address after signing up.
* - If **Confirm email** is enabled, a `user` is returned but `session` is null.
* - If **Confirm email** is disabled, both a `user` and a `session` are returned.
* - When the user confirms their email address, they are redirected to the [`SITE_URL`](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls) by default. You can modify your `SITE_URL` or add additional redirect URLs in [your project](/dashboard/project/_/auth/url-configuration).
* - If signUp() is called for an existing confirmed user:
* - When both **Confirm email** and **Confirm phone** (even when phone provider is disabled) are enabled in [your project](/dashboard/project/_/auth/providers), an obfuscated/fake user object is returned.
* - When either **Confirm email** or **Confirm phone** (even when phone provider is disabled) is disabled, the error message, `User already registered` is returned.
* - To fetch the currently logged-in user, refer to [`getUser()`](/docs/reference/javascript/auth-getuser).
*
* @example Sign up with an email and password
* ```js
* const { data, error } = await supabase.auth.signUp({
* email: 'example@email.com',
* password: 'example-password',
* })
* ```
*
* @exampleResponse Sign up with an email and password
* ```json
* // Some fields may be null if "confirm email" is enabled.
* {
* "data": {
* "user": {
* "id": "11111111-1111-1111-1111-111111111111",
* "aud": "authenticated",
* "role": "authenticated",
* "email": "example@email.com",
* "email_confirmed_at": "2024-01-01T00:00:00Z",
* "phone": "",
* "last_sign_in_at": "2024-01-01T00:00:00Z",
* "app_metadata": {
* "provider": "email",
* "providers": [
* "email"
* ]
* },
* "user_metadata": {},
* "identities": [
* {
* "identity_id": "22222222-2222-2222-2222-222222222222",
* "id": "11111111-1111-1111-1111-111111111111",
* "user_id": "11111111-1111-1111-1111-111111111111",
* "identity_data": {
* "email": "example@email.com",
* "email_verified": false,
* "phone_verified": false,
* "sub": "11111111-1111-1111-1111-111111111111"
* },
* "provider": "email",
* "last_sign_in_at": "2024-01-01T00:00:00Z",
* "created_at": "2024-01-01T00:00:00Z",
* "updated_at": "2024-01-01T00:00:00Z",
* "email": "example@email.com"
* }
* ],
* "created_at": "2024-01-01T00:00:00Z",
* "updated_at": "2024-01-01T00:00:00Z"
* },
* "session": {
* "access_token": "<ACCESS_TOKEN>",
* "token_type": "bearer",
* "expires_in": 3600,
* "expires_at": 1700000000,
* "refresh_token": "<REFRESH_TOKEN>",
* "user": {
* "id": "11111111-1111-1111-1111-111111111111",
* "aud": "authenticated",
* "role": "authenticated",
* "email": "example@email.com",
* "email_confirmed_at": "2024-01-01T00:00:00Z",
* "phone": "",
* "last_sign_in_at": "2024-01-01T00:00:00Z",
* "app_metadata": {
* "provider": "email",
* "providers": [
* "email"
* ]
* },
* "user_metadata": {},
* "identities": [
* {
* "identity_id": "22222222-2222-2222-2222-222222222222",
* "id": "11111111-1111-1111-1111-111111111111",
* "user_id": "11111111-1111-1111-1111-111111111111",
* "identity_data": {
* "email": "example@email.com",
* "email_verified": false,
* "phone_verified": false,
* "sub": "11111111-1111-1111-1111-111111111111"
* },
* "provider": "email",
* "last_sign_in_at": "2024-01-01T00:00:00Z",
* "created_at": "2024-01-01T00:00:00Z",
* "updated_at": "2024-01-01T00:00:00Z",
* "email": "example@email.com"
* }
* ],
* "created_at": "2024-01-01T00:00:00Z",
* "updated_at": "2024-01-01T00:00:00Z"
* }
* }
* },
* "error": null
* }
* ```
*
* @example Sign up with a phone number and password (SMS)
* ```js
* const { data, error } = await supabase.auth.signUp({
* phone: '123456789',
* password: 'example-password',
* options: {
* channel: 'sms'
* }
* })
* ```
*
* @exampleDescription Sign up with a phone number and password (whatsapp)
* The user will be sent a WhatsApp message which contains a OTP. By default, a given user can only request a OTP once every 60 seconds. Note that a user will need to have a valid WhatsApp account that is linked to Twilio in order to use this feature.
*
* @example Sign up with a phone number and password (whatsapp)
* ```js
* const { data, error } = await supabase.auth.signUp({
* phone: '123456789',
* password: 'example-password',
* options: {
* channel: 'whatsapp'
* }
* })
* ```
*
* @example Sign up with additional user metadata
* ```js
* const { data, error } = await supabase.auth.signUp(
* {
* email: 'example@email.com',
* password: 'example-password',
* options: {
* data: {
* first_name: 'John',
* age: 27,
* }
* }
* }
* )
* ```
*
* @exampleDescription Sign up with a redirect URL
* - See [redirect URLs and wildcards](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls) to add additional redirect URLs to your project.
*
* @example Sign up with a redirect URL
* ```js
* const { data, error } = await supabase.auth.signUp(
* {
* email: 'example@email.com',
* password: 'example-password',
* options: {
* emailRedirectTo: 'https://example.com/welcome'
* }
* }
* )
* ```
*/
async signUp(credentials: SignUpWithPasswordCredentials): Promise<AuthResponse> {
let flowId: string | null = null
try {
let res: AuthResponse
if ('email' in credentials) {
const { email, password, options } = credentials
let codeChallenge: string | null = null
let codeChallengeMethod: string | null = null
if (this.flowType === 'pkce') {
;[codeChallenge, codeChallengeMethod, flowId] = await this._getCodeChallengeAndMethod()
}
res = await _request(this.fetch, 'POST', `${this.url}/signup`, {
headers: this.headers,
redirectTo: this._maybeAppendFlowIdToRedirect(options?.emailRedirectTo, flowId),
body: {
email,
password,
data: options?.data ?? {},
gotrue_meta_security: { captcha_token: options?.captchaToken },
code_challenge: codeChallenge,
code_challenge_method: codeChallengeMethod,
},
xform: _sessionResponse,
})
} else if ('phone' in credentials) {
const { phone, password, options } = credentials
res = await _request(this.fetch, 'POST', `${this.url}/signup`, {
headers: this.headers,
body: {
phone,
password,
data: options?.data ?? {},
channel: options?.channel ?? 'sms',
gotrue_meta_security: { captcha_token: options?.captchaToken },
},
xform: _sessionResponse,
})
} else {
throw new AuthInvalidCredentialsError(
'You must provide either an email or phone number and a password'
)
}
const { data, error } = res
if (error || !data) {
await removePKCEVerifier(this.storage, this.storageKey, flowId)
return this._returnResult({ data: { user: null, session: null }, error: error })
}
const session: Session | null = data.session
const user: User | null = data.user
if (data.session) {
await this._saveSession(data.session)
await this._notifyAllSubscribers('SIGNED_IN', session)
}
return this._returnResult({ data: { user, session }, error: null })
} catch (error) {
await removePKCEVerifier(this.storage, this.storageKey, flowId)
if (isAuthError(error)) {
return this._returnResult({ data: { user: null, session: null }, error })
}
throw error
}
}
/**
* 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.
*
* @category Auth
*
* @remarks
* - Requires either an email and password or a phone number and password.
*
* @example Sign in with email and password
* ```js
* const { data, error } = await supabase.auth.signInWithPassword({
* email: 'example@email.com',
* password: 'example-password',
* })
* ```
*
* @exampleResponse Sign in with email and password
* ```json
* {
* "data": {
* "user": {
* "id": "11111111-1111-1111-1111-111111111111",
* "aud": "authenticated",
* "role": "authenticated",
* "email": "example@email.com",
* "email_confirmed_at": "2024-01-01T00:00:00Z",
* "phone": "",
* "last_sign_in_at": "2024-01-01T00:00:00Z",
* "app_metadata": {
* "provider": "email",
* "providers": [
* "email"
* ]
* },
* "user_metadata": {},
* "identities": [
* {
* "identity_id": "22222222-2222-2222-2222-222222222222",
* "id": "11111111-1111-1111-1111-111111111111",
* "user_id": "11111111-1111-1111-1111-111111111111",
* "identity_data": {
* "email": "example@email.com",
* "email_verified": false,
* "phone_verified": false,
* "sub": "11111111-1111-1111-1111-111111111111"
* },
* "provider": "email",
* "last_sign_in_at": "2024-01-01T00:00:00Z",
* "created_at": "2024-01-01T00:00:00Z",
* "updated_at": "2024-01-01T00:00:00Z",
* "email": "example@email.com"
* }
* ],
* "created_at": "2024-01-01T00:00:00Z",
* "updated_at": "2024-01-01T00:00:00Z"
* },
* "session": {
* "access_token": "<ACCESS_TOKEN>",
* "token_type": "bearer",
* "expires_in": 3600,
* "expires_at": 1700000000,
* "refresh_token": "<REFRESH_TOKEN>",
* "user": {
* "id": "11111111-1111-1111-1111-111111111111",
* "aud": "authenticated",
* "role": "authenticated",
* "email": "example@email.com",
* "email_confirmed_at": "2024-01-01T00:00:00Z",
* "phone": "",
* "last_sign_in_at": "2024-01-01T00:00:00Z",
* "app_metadata": {
* "provider": "email",
* "providers": [
* "email"
* ]
* },
* "user_metadata": {},
* "identities": [
* {
* "identity_id": "22222222-2222-2222-2222-222222222222",
* "id": "11111111-1111-1111-1111-111111111111",
* "user_id": "11111111-1111-1111-1111-111111111111",
* "identity_data": {
* "email": "example@email.com",
* "email_verified": false,
* "phone_verified": false,
* "sub": "11111111-1111-1111-1111-111111111111"
* },
* "provider": "email",
* "last_sign_in_at": "2024-01-01T00:00:00Z",
* "created_at": "2024-01-01T00:00:00Z",
* "updated_at": "2024-01-01T00:00:00Z",
* "email": "example@email.com"
* }
* ],
* "created_at": "2024-01-01T00:00:00Z",
* "updated_at": "2024-01-01T00:00:00Z"
* }
* }
* },
* "error": null
* }
* ```
*
* @example Sign in with phone and password
* ```js
* const { data, error } = await supabase.auth.signInWithPassword({
* phone: '+13334445555',
* password: 'some-password',
* })
* ```
*
* @exampleDescription Handling errors
* Log the full `error` object so fields like `code`, `status`, and `name` aren't hidden. The `error.code` (e.g. `'invalid_credentials'`, `'email_not_confirmed'`) is often more useful for branching than `error.message`, and the full object surfaces both.
*
* @example Handling errors
* ```js
* const { data, error } = await supabase.auth.signInWithPassword({
* email: 'example@email.com',
* password: 'example-password',
* })
* if (error) {
* console.error(error)
* return
* }
* ```
*/
async signInWithPassword(
credentials: SignInWithPasswordCredentials
): Promise<AuthTokenResponsePassword> {
try {
let res: AuthResponsePassword
if ('email' in credentials) {
const { email, password, options } = credentials
res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=password`, {
headers: this.headers,
body: {
email,
password,
gotrue_meta_security: { captcha_token: options?.captchaToken },
},
xform: _sessionResponsePassword,
})
} else if ('phone' in credentials) {
const { phone, password, options } = credentials
res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=password`, {
headers: this.headers,
body: {
phone,
password,
gotrue_meta_security: { captcha_token: options?.captchaToken },
},
xform: _sessionResponsePassword,
})
} else {
throw new AuthInvalidCredentialsError(
'You must provide either an email or phone number and a password'
)
}
const { data, error } = res
if (error) {
return this._returnResult({ data: { user: null, session: null }, error })
} else if (!data || !data.session || !data.user) {
const invalidTokenError = new AuthInvalidTokenResponseError()
return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError })
}
if (data.session) {
await this._saveSession(data.session)
await this._notifyAllSubscribers('SIGNED_IN', data.session)
}
return this._returnResult({
data: {
user: data.user,
session: data.session,
...(data.weak_password ? { weakPassword: data.weak_password } : null),
},
error,
})
} catch (error) {
if (isAuthError(error)) {
return this._returnResult({ data: { user: null, session: null }, error })
}
throw error
}
}
/**
* Log in an existing user via a third-party provider.
* This method supports the PKCE flow.
*
* @category Auth
*
* @remarks
* - This method is used for signing in using [Social Login (OAuth) providers](/docs/guides/auth#configure-third-party-providers).
* - It works by redirecting your application to the provider's authorization screen, before bringing back the user to your app.
*
* @example Sign in using a third-party provider
* ```js
* const { data, error } = await supabase.auth.signInWithOAuth({
* provider: 'github'
* })
* ```
*
* @exampleResponse Sign in using a third-party provider
* ```json
* {
* data: {
* provider: 'github',
* url: <PROVIDER_URL_TO_REDIRECT_TO>,
* flowId: <PKCE_FLOW_ID_OR_NULL>
* },
* error: null
* }
* ```
*
* @exampleDescription Sign in using a third-party provider with redirect
* - When the OAuth provider successfully authenticates the user, they are redirected to the URL specified in the `redirectTo` parameter. This parameter defaults to the [`SITE_URL`](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls). It does not redirect the user immediately after invoking this method.
* - See [redirect URLs and wildcards](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls) to add additional redirect URLs to your project.
*
* @example Sign in using a third-party provider with redirect
* ```js
* const { data, error } = await supabase.auth.signInWithOAuth({
* provider: 'github',
* options: {
* redirectTo: 'https://example.com/welcome'
* }
* })
* ```
*
* @exampleDescription Sign in with scopes and access provider tokens
* If you need additional access from an OAuth provider, in order to access provider specific APIs in the name of the user, you can do this by passing in the scopes the user should authorize for your application. Note that the `scopes` option takes in **a space-separated list** of scopes.
*
* Because OAuth sign-in often includes redirects, you should register an `onAuthStateChange` callback immediately after you create the Supabase client. This callback will listen for the presence of `provider_token` and `provider_refresh_token` properties on the `session` object and store them in local storage. The client library will emit these values **only once** immediately after the user signs in. You can then access them by looking them up in local storage, or send them to your backend servers for further processing.
*
* Finally, make sure you remove them from local storage on the `SIGNED_OUT` event. If the OAuth provider supports token revocation, make sure you call those APIs either from the frontend or schedule them to be called on the backend.
*
* @example Sign in with scopes and access provider tokens
* ```js
* // 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'
* }
* })
* ```
*/
async signInWithOAuth(credentials: SignInWithOAuthCredentials): Promise<OAuthResponse> {
return await this._handleProviderSignIn(credentials.provider, {
redirectTo: credentials.options?.redirectTo,
scopes: credentials.options?.scopes,
queryParams: credentials.options?.queryParams,
skipBrowserRedirect: credentials.options?.skipBrowserRedirect,
})
}
/**
* Log in an existing user by exchanging an Auth Code issued during the PKCE flow.
*
* @category Auth
*
* @remarks
* - Used when `flowType` is set to `pkce` in client options.
* - When several PKCE flows are in flight at once, pass `options.flowId` so
* the code is exchanged with the verifier created by that specific flow.
* The flow id is returned by `signInWithOAuth`, and with
* `experimental.appendPkceFlowIdToRedirects` enabled it also arrives on
* your callback URL as the reserved `sb_flow_id` query parameter (read
* automatically in a browser).
* - When a flow id is present but its stored verifier is gone (evicted,
* already used, or from another device), the call fails with a verifier
* missing error instead of trying another flow's verifier — a mismatched
* verifier would consume the single-use code. Without any flow id the
* most recently stored verifier is used, as before.
*
* @example Exchange Auth Code
* ```js
* supabase.auth.exchangeCodeForSession('34e770dd-9ff9-416c-87fa-43b31d7ef225')
* ```
*
* @example Exchange Auth Code for a specific flow (e.g. in a server-side callback handler)
* ```js
* const flowId = requestUrl.searchParams.get('sb_flow_id')
* supabase.auth.exchangeCodeForSession(code, flowId ? { flowId } : undefined)
* ```
*
* @exampleResponse Exchange Auth Code
* ```json
* {
* "data": {
* session: {
* access_token: '<ACCESS_TOKEN>',
* token_type: 'bearer',
* expires_in: 3600,
* expires_at: 1700000000,
* refresh_token: '<REFRESH_TOKEN>',
* user: {
* id: '11111111-1111-1111-1111-111111111111',
*