@supabase/gotrue-js
Version:
Official SDK for Supabase Auth
1,122 lines • 267 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const GoTrueAdminApi_1 = tslib_1.__importDefault(require("./GoTrueAdminApi"));
const constants_1 = require("./lib/constants");
const errors_1 = require("./lib/errors");
const fetch_1 = require("./lib/fetch");
const helpers_1 = require("./lib/helpers");
const local_storage_1 = require("./lib/local-storage");
const locks_1 = require("./lib/locks");
const polyfills_1 = require("./lib/polyfills");
const version_1 = require("./lib/version");
const base64url_1 = require("./lib/base64url");
const ethereum_1 = require("./lib/web3/ethereum");
const webauthn_1 = require("./lib/webauthn");
(0, polyfills_1.polyfillGlobalThis)(); // Make "globalThis" available
const DEFAULT_OPTIONS = {
url: constants_1.GOTRUE_URL,
storageKey: constants_1.STORAGE_KEY,
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: true,
headers: constants_1.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(name, acquireTimeout, fn) {
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 = {};
class GoTrueClient {
/**
* The JWKS used for verifying asymmetric JWTs
*/
get jwks() {
var _a, _b;
return (_b = (_a = GLOBAL_JWKS[this.storageKey]) === null || _a === void 0 ? void 0 : _a.jwks) !== null && _b !== void 0 ? _b : { keys: [] };
}
set jwks(value) {
GLOBAL_JWKS[this.storageKey] = Object.assign(Object.assign({}, GLOBAL_JWKS[this.storageKey]), { jwks: value });
}
get jwks_cached_at() {
var _a, _b;
return (_b = (_a = GLOBAL_JWKS[this.storageKey]) === null || _a === void 0 ? void 0 : _a.cachedAt) !== null && _b !== void 0 ? _b : Number.MIN_SAFE_INTEGER;
}
set jwks_cached_at(value) {
GLOBAL_JWKS[this.storageKey] = Object.assign(Object.assign({}, GLOBAL_JWKS[this.storageKey]), { cachedAt: value });
}
/**
* 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) {
var _a, _b, _c;
/**
* @experimental
*/
this.userStorage = null;
this.memoryStorage = null;
this.stateChangeEmitters = new Map();
this.autoRefreshTicker = null;
this.autoRefreshTickTimeout = null;
this.visibilityChangedCallback = null;
this.refreshingDeferred = 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.
*/
this.lastRefreshFailure = 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).
*/
this._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
*/
this.initializePromise = 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.
*/
this._pendingInitNotifications = null;
this.detectSessionInUrl = true;
this.hasCustomAuthorizationHeader = false;
this.suppressGetSessionWarning = false;
/**
* 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.
*/
this.lock = null;
this.lockAcquired = false;
this.pendingInLock = [];
/**
* Used to broadcast state change events to other tabs listening.
*/
this.broadcastChannel = null;
this.logger = console.log;
const settings = Object.assign(Object.assign({}, DEFAULT_OPTIONS), options);
this.storageKey = settings.storageKey;
this.instanceID = (_a = GoTrueClient.nextInstanceID[this.storageKey]) !== null && _a !== void 0 ? _a : 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 && (0, helpers_1.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 = (_b = settings.experimental) !== null && _b !== void 0 ? _b : {};
this.admin = new GoTrueAdminApi_1.default({
url: settings.url,
headers: settings.headers,
fetch: settings.fetch,
experimental: this.experimental,
});
this.url = settings.url;
this.headers = settings.headers;
this.fetch = (0, helpers_1.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 webauthn_1.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 ((0, helpers_1.supportsLocalStorage)()) {
this.storage = globalThis.localStorage;
}
else {
this.memoryStorage = {};
this.storage = (0, local_storage_1.memoryLocalStorageAdapter)(this.memoryStorage);
}
}
if (settings.userStorage) {
this.userStorage = settings.userStorage;
}
}
else {
this.memoryStorage = {};
this.storage = (0, local_storage_1.memoryLocalStorageAdapter)(this.memoryStorage);
}
if ((0, helpers_1.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);
}
(_c = this.broadcastChannel) === null || _c === void 0 ? void 0 : _c.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.
*/
isThrowOnErrorEnabled() {
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.
*/
_returnResult(result) {
if (this.throwOnError && result && result.error) {
throw result.error;
}
return result;
}
_logPrefix() {
return ('GoTrueClient@' +
`${this.storageKey}:${this.instanceID} (${version_1.version}) ${new Date().toISOString()}`);
}
_debug(...args) {
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() {
var _a;
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 = (_a = this._pendingInitNotifications) !== null && _a !== void 0 ? _a : [];
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
*/
async _initialize() {
var _a;
try {
let params = {};
let callbackUrlType = 'none';
if ((0, helpers_1.isBrowser)()) {
params = (0, helpers_1.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 ((0, helpers_1.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 ((0, errors_1.isAuthImplicitGrantRedirectError)(error)) {
const errorCode = (_a = error.details) === null || _a === void 0 ? void 0 : _a.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 ((0, errors_1.isAuthError)(error)) {
return this._returnResult({ error });
}
return this._returnResult({
error: new errors_1.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) {
var _a, _b, _c;
try {
const res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/signup`, {
headers: this.headers,
body: {
data: (_b = (_a = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : {},
gotrue_meta_security: { captcha_token: (_c = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _c === void 0 ? void 0 : _c.captchaToken },
},
xform: fetch_1._sessionResponse,
});
const { data, error } = res;
if (error || !data) {
return this._returnResult({ data: { user: null, session: null }, error: error });
}
const session = data.session;
const user = 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 ((0, errors_1.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) {
var _a, _b, _c;
let flowId = null;
try {
let res;
if ('email' in credentials) {
const { email, password, options } = credentials;
let codeChallenge = null;
let codeChallengeMethod = null;
if (this.flowType === 'pkce') {
;
[codeChallenge, codeChallengeMethod, flowId] = await this._getCodeChallengeAndMethod();
}
res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/signup`, {
headers: this.headers,
redirectTo: this._maybeAppendFlowIdToRedirect(options === null || options === void 0 ? void 0 : options.emailRedirectTo, flowId),
body: {
email,
password,
data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {},
gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
code_challenge: codeChallenge,
code_challenge_method: codeChallengeMethod,
},
xform: fetch_1._sessionResponse,
});
}
else if ('phone' in credentials) {
const { phone, password, options } = credentials;
res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/signup`, {
headers: this.headers,
body: {
phone,
password,
data: (_b = options === null || options === void 0 ? void 0 : options.data) !== null && _b !== void 0 ? _b : {},
channel: (_c = options === null || options === void 0 ? void 0 : options.channel) !== null && _c !== void 0 ? _c : 'sms',
gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
},
xform: fetch_1._sessionResponse,
});
}
else {
throw new errors_1.AuthInvalidCredentialsError('You must provide either an email or phone number and a password');
}
const { data, error } = res;
if (error || !data) {
await (0, helpers_1.removePKCEVerifier)(this.storage, this.storageKey, flowId);
return this._returnResult({ data: { user: null, session: null }, error: error });
}
const session = data.session;
const user = 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 (0, helpers_1.removePKCEVerifier)(this.storage, this.storageKey, flowId);
if ((0, errors_1.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) {
try {
let res;
if ('email' in credentials) {
const { email, password, options } = credentials;
res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=password`, {
headers: this.headers,
body: {
email,
password,
gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
},
xform: fetch_1._sessionResponsePassword,
});
}
else if ('phone' in credentials) {
const { phone, password, options } = credentials;
res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=password`, {
headers: this.headers,
body: {
phone,
password,
gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
},
xform: fetch_1._sessionResponsePassword,
});
}
else {
throw new errors_1.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 errors_1.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: Object.assign({ user: data.user, session: data.session }, (data.weak_password ? { weakPassword: data.weak_password } : null)),
error,
});
}
catch (error) {
if ((0, errors_1.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) {
var _a, _b, _c, _d;
return await this._handleProviderSignIn(credentials.provider, {
redirectTo: (_a = credentials.options) === null || _a === void 0 ? void 0 : _a.redirectTo,
scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes,
queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams,
skipBrowserRedirect: (_d = credentials.options) === null || _d === void 0 ? void 0 : _d.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',
* aud: 'authenticated',
* role: 'authenticated',
* email: 'example@email.com'
* email_confirmed_at: '2024-01-01T00:00:00Z',
* phone: '',
* confirmation_sent_at: '2024-01-01T00:00:00Z',
* confirmed_at: '2024-01-01T00:00:00Z',
* last_sign_in_at: '2024-01-01T00:00:00Z',
* app_metadata: {
* "provider": "email",
* "providers": [
* "email",
* "<OTHER_PROVIDER>"
* ]
* },
* user_metadata: {
* email: 'email@email.com',
* email_verified: true,
* full_name: 'User Name',
* iss: '<ISS>',
* name: 'User Name',
* phone_verified: false,
* provider_id: '<PROVIDER_ID>',