swift Client Library
supabase-swiftView on GitHubThis reference documents every object and method available in v3 of the Supabase Swift library. The source is in the supabase-swift repository on GitHub. With supabase-swift, you can query and update your Postgres data, listen to database changes, and invoke Deno Edge Functions. You can also sign users up and in, and upload, download, and delete large files.
v3 is in alpha. Its API can change before the stable release. To move an app from v2, read the upgrade guide.
Installing
Install using Swift Package Manager
v3 needs Xcode 26.0 or later and Swift 6.2 or later. It supports iOS 16, macOS 13, tvOS 16, watchOS 9, and visionOS 1 or later.
The package exposes multiple libraries. Add Supabase to get all of them, or add only the ones you need:
AuthFunctionsPostgRESTRealtimeStorage
In Package.swift, replace YOUR_TARGET_NAME with the name of your target.
If you use Xcode, follow Apple's dependencies guide to add supabase-swift to your project. Use https://github.com/supabase/supabase-swift.git for the URL and 3.0.0-alpha.2 for the version. Xcode picks a prerelease version only when the version rule names one.
// swift-tools-version:6.2let package = Package( ... dependencies: [ ... .package( url: "https://github.com/supabase/supabase-swift.git", from: "3.0.0-alpha.2" ), ], targets: [ .target( name: "YOUR_TARGET_NAME", dependencies: [ .product( name: "Supabase", // Auth, Functions, PostgREST, Realtime, or Storage package: "supabase-swift" ), ] ) ])Enable Data API access
supabase-swift uses the Data API to query and mutate your Postgres data. You first need to grant Data API roles permissions to access your tables and functions.
In Data API integrations settings, expose the specific tables and functions that your app queries or calls. To automatically grant access for new tables and functions in public, enable Default privileges for new entities.
Alternatively, grant the permissions with SQL. Run the following SQL using the SQL Editor in the Supabase Dashboard or with psql over a direct connection. To connect with psql, see Direct connection.
In the SQL, replace YOUR_TABLE and YOUR_FUNCTION with the names of your table and function.
-- Before granting access to client roles, make sure Row Level Security (RLS)-- is enabled and create the policies required for each role's allowed operations.alter table public.YOUR_TABLE enable row level security;-- create policy ... on public.YOUR_TABLE ...;-- Grant least-privilege access to tables after RLS and policies are in placegrant select on public.YOUR_TABLE to anon;grant select, insert, update, delete on public.YOUR_TABLE to authenticated;grant all on public.YOUR_TABLE to service_role;-- Grant execute on functions after verifying any table access they rely ongrant execute on function public.YOUR_FUNCTION to authenticated, service_role;Initializing
Create a SupabaseClient with your Project URL and your publishable key. You can find them in your project's Project Settings → API Keys. The Supabase client is your entrypoint to the rest of the Supabase functionality and is the easiest way to interact with everything we offer within the Supabase ecosystem.
The initializer throws a SupabaseClientError when the URL has no scheme or no host, so call it with try. Create the client once and share it: it holds the session and the Realtime connection.
- Use only a publishable key in an app. A secret key gives full access to your project, so keep it on a server.
- Pass settings in a
SupabaseClient.Configuration. It has one group for each module (database,auth,functions,realtime,storage) and aglobalgroup for all of them. - Debug builds log warnings and errors to stderr by default. Release builds stay silent.
import Supabaselet supabase = try SupabaseClient( supabaseURL: URL(string: "https://xyzcompany.supabase.co")!, supabaseKey: "your-publishable-key")Upgrade guide
Upgrade your app from supabase-swift v2 to v3 and fix the compile errors that the upgrade causes. v3 renames many public types and methods, so most errors come from a rename. This page covers the changes that affect every app.
For the full list, including the changes that still compile but behave differently, see the supabase-swift repository on GitHub. It has the v3 migration guide and the module guides for Auth, PostgREST, Storage, Functions, and Realtime.
Upgrade the client library
- Install Xcode 26.0 or later. v3 needs Swift 6.2 or later, which Xcode 26.0 includes.
- Update the supabase-swift package requirement to
3.0.0-alpha.2. - If your app pins swift-crypto below 4.0.0, raise the pin to 4.0.0 or later. v3 needs swift-crypto 4.0.0 or later.
.package(url: "https://github.com/supabase/supabase-swift", from: "3.0.0-alpha.2")Create the client with a configuration
v3 renames SupabaseClientOptions to SupabaseClient.Configuration, and the initializer label is configuration:. The nested types drop their Options suffix, and db is renamed to database.
In v3, every client initializer throws when the URL has no scheme or no host. Add try.
Headers are HTTPFields. Write each key as an HTTPField.Name.
let client = SupabaseClient( supabaseURL: url, supabaseKey: key, options: SupabaseClientOptions( db: .init(schema: "app"), global: .init(headers: ["x-app": "demo"]) ))var configuration = SupabaseClient.Configuration()configuration.database.schema = "app"configuration.global.headers = [HTTPField.Name("x-app")!: "demo"]let client = try SupabaseClient( supabaseURL: url, supabaseKey: key, configuration: configuration)Use swift-log for logging
In v3, every logger: parameter takes a Logging.Logger from the swift-log package on GitHub. v3 removes SupabaseLogger and OSLogSupabaseLogger. Add swift-log to your package and import Logging where you build the logger.
When you pass no logger, debug builds log warnings and errors to stderr. Release builds stay silent.
import Loggingimport Supabasevar logger = Logger(label: "myapp")logger.logLevel = .debuglet client = try SupabaseClient( supabaseURL: url, supabaseKey: key, configuration: .init(global: .init(logger: logger)))Replace fetch closures and URLSession options
v3 replaces the fetch closures and the URLSession options with a transport and middleware. Every client sends requests through one ClientTransport behind an ordered list of ClientMiddleware. Both go in one HTTPClientConfiguration, passed as http:. URLSessionTransport(session:) wraps the URLSession that you used in v2.
In v3, the SDK sets the request timeout itself: 60 seconds, or 150 seconds for Functions. To change it, set HTTPClientConfiguration(timeout:).
let client = SupabaseClient( supabaseURL: url, supabaseKey: key, options: .init(global: .init(session: mySession)))let client = try SupabaseClient( supabaseURL: url, supabaseKey: key, configuration: .init( global: .init(http: .init(transport: URLSessionTransport(session: mySession))) ))Catch errors by module
v3 removes HTTPError. Each module throws its own error type: AuthError, PostgrestError, StorageError, FunctionsError, or RealtimeError. Each one conforms to SupabaseError and has a kind, a code, the response, and an underlyingError.
The SDK wraps a URLError or DecodingError in the module error and keeps the original in underlyingError. In v3, a canceled task throws CancellationError in every module.
Errors that your own transport or middleware throws reach you unchanged. Keep the handlers for those errors.
do { try await supabase.from("todos").insert(todo).execute()} catch PostgrestError.Code.uniqueViolation { showDuplicate()} catch PostgrestError.Kind.transport { showOfflineBanner()} catch let error as any SupabaseError { if let response = error.response { print(response.status.code, String(decoding: response.body, as: UTF8.self)) }}Other renames and removals
v3 also renames the following methods, types, and arguments:
AnyJSONis renamed toJSONValue. Numbers are one case,.number(JSONNumber), which keeps every digit.supabase.realtimeV2is renamed tosupabase.realtime, andsupabase.channel(_:)isasync.supabase.handle(_:)is renamed tosupabase.handleRedirect(_:).- Methods that only read a value drop their
getprefix. For example,getPublicURLispublicURL. - Arguments that name an identifier are
id:, and acronyms keep their capitals, as infactorID.
v3 removes the following:
supabase.database. Usesupabase.from(_:),supabase.rpc(_:), andsupabase.schema(_:).- Every type, method, and property that was deprecated in v2.55.4.
Fetch data
- By default, Supabase projects will return a maximum of 1,000 rows. This setting can be changed in Project API Settings. It's recommended that you keep it low to limit the payload size of accidental or malicious requests. You can use
range()queries to paginate through your data. select()can be combined with Modifiersselect()can be combined with Filters- If using the Supabase hosted platform
apikeyis technically a reserved keyword, since the API gateway will pluck it out for authentication. It should be avoided as a column name. - Read the decoded rows from the
valueproperty of the response. Declare aDecodabletype and annotate the variable, so the client knows what to decode. - Failed queries throw a
PostgrestError. Itscodeholds the PostgreSQL or PostgREST error code, such asPGRST116. - v3 also has an experimental typed query API: the
@Tablemacro andfrom(Todo.self). It needs@_spi(Experimental) import Supabaseand can change in a minor release. The examples on this page use the string-based API.
struct Instrument: Decodable { let id: Int let name: String}let instruments: [Instrument] = try await supabase .from("instruments") .select() .execute() .valueInsert data
insert()returns no rows by default. Addselect()to the chain to get the inserted rows back.- You can't add filters after
insert(). Modifiers such asselect()andsingle()still work. - If
valuesfails to encode,insert()throws aPostgrestErrorof kind.invalidRequestand sends no request.
struct Instrument: Encodable { let id: Int let name: String}let instrument = Instrument(id: 1, name: "ukelele")try await supabase .from("instruments") .insert(instrument) .execute()Update data
update()should always be combined with Filters to target the item(s) you wish to update.update()returns no rows by default. Addselect()after the filters to get the updated rows back.
try await supabase .from("instruments") .update(["name": "piano"]) .eq("id", value: 1) .execute()Upsert data
- Primary keys must be included in
valuesto use upsert. upsert()returns no rows by default. Addselect()to the chain to get the rows back.- You can't add filters after
upsert(). Modifiers such asselect()andsingle()still work.
struct Instrument: Encodable { let id: Int let name: String}try await supabase .from("instruments") .upsert(Instrument(id: 1, name: "piano")) .execute()Delete data
delete()should always be combined with filters to target the item(s) you wish to delete.- If you use
delete()with filters and you have RLS enabled, only rows visible throughSELECTpolicies are deleted. Note that by default no rows are visible, so you need at least oneSELECT/ALLpolicy that makes the rows visible. delete()returns no rows by default. Addselect()after the filters to get the deleted rows back.
try await supabase .from("instruments") .delete() .eq("id", value: 1) .execute()Limit the rows an update or delete affects
Set the maximum number of rows that can be affected by the query.
Only available in PostgREST v13+ and only works with PATCH, DELETE methods and RPC calls.
- This method sets
handling=strictandmax-affected=<value>headers for row limit enforcement. - Only use with UPDATE (PATCH), DELETE operations, or RPC calls that modify data.
- If the query would affect more rows than specified, PostgREST will return an error.
- This is useful for preventing accidental bulk updates or deletes.
try await supabase .from("users") .update(["status": "active"]) .eq("id", value: 1) .maxAffected(1) .execute()Call a Postgres function
You can call Postgres functions as Remote Procedure Calls, logic in your database that you can execute from anywhere. Functions are useful when the logic rarely changes—like for password resets and updates.
rpc() throws a PostgrestError of kind .invalidRequest if params fails to encode. It sends no request in that case.
create or replace function hello_world() returns text as $$ select 'Hello world';$$ language sql;let value: String = try await supabase .rpc("hello_world") .execute() .valueUsing filters
Filters allow you to only return rows that match certain conditions.
Filters can be used on select(), update(), and delete() queries. insert() and upsert() don't take filters.
If a Postgres function returns a table response, you can also apply filters.
A filter value is any type that conforms to PostgrestFilterValue. String, the integer and floating-point types, Decimal, Bool, UUID, Date, JSONValue, and arrays of these conform already. Conform your own types to use them as filter values.
nil is not a filter value, so eq("column", value: nil) doesn't compile. Use is("column", value: nil) to match NULL.
The filter methods are eq, neq, gt, gte, lt, lte, like, ilike, is, in, notIn, contains, containedBy, rangeLt, rangeGt, rangeGte, rangeLte, rangeAdjacent, overlaps, and textSearch. Check available operators in PostgREST.
try await supabase .from("cities") .select("name, country_id") .eq("name", value: "The Shire") // Correcttry await supabase .from("citites") .eq("name", value: "The Shire") // Incorrect .select("name, country_id")Column is equal to a value
Match only rows where column is equal to value.
try await supabase .from("cities") .select("name, country_id") .eq("name", value: "The shire") .execute()Column is not equal to a value
Match only rows where column is not equal to value.
try await supabase .from("cities") .select("name, country_id") .neq("name", value: "Paris") .execute()Column is greater than a value
Match only rows where column is greater than value.
try await supabase .from("cities") .select("name, country_id") .gt("country_id", value: 250) .execute()Column is greater than or equal to a value
Match only rows where column is greater than or equal to value.
try await supabase .from("cities") .select("name, country_id") .gte("country_id", value: 250) .execute()Column is less than a value
Match only rows where column is less than value.
try await supabase .from("cities") .select("name, country_id") .lt("country_id", value: 250) .execute()Column is less than or equal to a value
Match only rows where column is less than or equal to value.
try await supabase .from("cities") .select("name, country_id") .lte("country_id", value: 250) .execute()Column matches a pattern
Match only rows where column matches pattern case-sensitively.
try await supabase .from("cities") .select("name, country_id") .like("name", pattern: "%la%") .execute()Column matches a case-insensitive pattern
Match only rows where column matches pattern case-insensitively.
try await supabase .from("cities") .select("name, country_id") .ilike("name", pattern: "%la%") .execute()Column is a value
Match only rows where column IS value. value is nil, true, or false.
Use is() to match NULL. eq() doesn't take nil.
try await supabase .from("cities") .select("name, country_id") .is("name", value: nil) .execute()Column is in an array
Match only rows where column is included in the values array.
try await supabase .from("cities") .select("name, country_id") .in("name", values: ["Rio de Janeiro", "San Francisco"]) .execute()Column is not in an array
Match only rows where column is not included in the values array. The negation of in().
try await supabase .from("cities") .select("name, country_id") .notIn("name", values: ["Rio de Janeiro", "San Francisco"]) .execute()Column contains every element in a value
Match only rows where column contains every element appearing in value.
try await supabase .from("cities") .select("name, main_exports") .contains("main_exports", value: ["oil"]) .execute()Contained by value
Match only rows where every element in column appears in value.
try await supabase .from("cities") .select("name, main_exports") .containedBy("main_exports", value: ["cars", "food", "machine"]) .execute()Greater than a range
Match only rows where every element in column is greater than any element in range.
try await supabase .from("reservations") .select() .rangeGt("during", range: "[2000-01-02 08:30, 2000-01-02 09:30)") .execute()Greater than or equal to a range
Match only rows where every element in column is either contained in range or greater than any element in range.
try await supabase .from("reservations") .select() .rangeGte("during", range: "[2000-01-02 08:30, 2000-01-02 09:30)") .execute()Less than a range
Match only rows where every element in column is less than any element in range.
try await supabase .from("reservations") .select() .rangeLt("during", range: "[2000-01-02 08:30, 2000-01-02 09:30)") .execute()Less than or equal to a range
Match only rows where every element in column is either contained in range or less than any element in range.
try await supabase .from("reservations") .select() .rangeLte("during", range: "[2000-01-02 08:30, 2000-01-02 09:30)") .execute()Mutually exclusive to a range
Match only rows where column is adjacent to range.
try await supabase .from("reservations") .select() .rangeAdjacent("during", range: "[2000-01-02 08:30, 2000-01-02 09:30)") .execute()With a common element
Match only rows where column and value have an element in common.
try await supabase .from("cities") .select("name, main_exports") .overlaps("main_exports", value: ["exports", "tourism"]) .execute()Match a string
Match only rows where column matches the query string in query.
configsets the text search configuration, such as"english".typepicks howqueryis parsed:.plain,.phrase, or.websearch. Leave it out to useto_tsquery.
try await supabase .from("quotes") .select("catchphrase") .textSearch("catchphrase", query: "'fat' & 'cat'", config: "english") .execute()Match an associated value
try await supabase .from("instruments") .select("name") .match(["id": 2, "name": "viola"]) .execute()Don't match the filter
Finds all rows that don't satisfy the filter.
-
.not()expects you to use the raw PostgREST syntax for the filter names and values..not("name", operator: .eq, value: "violin").not("arraycol", operator: .cs, value: #"{"a","b"}"#) // Use Postgres array {} for array column and 'cs' for contains..not("rangecol", operator: .cs, value: "(1,2]") // Use Postgres range syntax for range column..not("id", operator: .in, value: "(6,7)") // Use Postgres list () and 'in' for in_ filter..not("id", operator: .in, value: "(\(myList.map(String.init).joined(separator: ",")))") // You can insert a Swift array.
try await supabase .from("instruments") .select() .not("name", operator: .is, value: "null") .execute()Match at least one filter
or() expects you to use the raw PostgREST syntax for the filter names and values.
.or(#"id.in.(5,6,7), arraycol.cs.{"a","b"}"#) // Use `()` for `in` filter, `{}` for array values and `cs` for `contains()`..or(#"id.in.(5,6,7), arraycol.cd.{"a","b"}"#) // Use `cd` for `containedBy()`try await supabase .from("instruments") .select("name") .or("id.eq.2,name.eq.cello") .execute()Match the filter
filter() expects you to use the raw PostgREST syntax for the filter values.
.filter("id", operator: "in", value: "(5,6,7)") // Use `()` for `in` filter.filter("arraycol", operator: "cs", value: #"{"a","b"}"#) // Use `cs` for `contains()`, `{}` for array valuestry await supabase .from("instruments") .select() .filter("name", operator: "in", value: #"("cello","guzheng")"#) .execute()Using modifiers
Filters work on the row level—they allow you to return rows that only match certain conditions without changing the shape of the rows. Modifiers are everything that don't fit that definition—allowing you to change the format of the response (e.g. returning a CSV string).
Modifiers must be specified after filters. Some modifiers only apply for queries that return rows (e.g., select() or rpc() on a function that returns a table response).
Return data after inserting
Perform a SELECT on the query result.
insert(), update(), upsert(), and delete() return no rows by default. Add select() to the chain to get the changed rows back.
struct Instrument: Codable { let id: Int let name: String}let instruments: [Instrument] = try await supabase .from("instruments") .upsert(Instrument(id: 1, name: "piano")) .select() .execute() .valueOrder the results
Order the query result by column.
nullsFirstdefaults tonil, so the database picks whereNULLvalues go: last on an ascending sort, first on a descending sort. Passtrueorfalseto choose.
try await supabase .from("instruments") .select("id, name") .order("id", ascending: false) .execute()Limit the number of rows returned
Limit the query result by count.
try await supabase .from("instruments") .select("id, name") .limit(1) .execute()Limit the query to a range
Limit the query result by from and to inclusively.
try await supabase .from("instruments") .select("name") .range(from: 0, to: 1) .execute()Retrieve one row of data
By default PostgREST returns all JSON results in an array, even when there is only one item. Use single() to return the object without the array.
The query must match exactly one row. Otherwise the call throws a PostgrestError with code PGRST116.
try await supabase .from("instruments") .select("name") .limit(1) .single() .execute()Retrieve zero or one row of data
Return at most one row. When no row matches, value is nil. Decode into an optional type to get the nil.
- When more than one row matches, the call throws a
PostgrestErrorwith codePGRST116and status 406, the same error thatsingle()throws. maybeSingle()requests the usual JSON array and counts the rows in the client. On a write, such asupdate(...).select().maybeSingle(), every matched row is written before the count is checked. Usesingle()if PostgREST must roll back the write when more than one row matches.
let todo: Todo? = try await supabase .from("todos") .select() .eq("id", value: 42) .maybeSingle() .execute() .valueRetrieve as a CSV
let csv = try await supabase .from("instruments") .select() .csv() .execute() .string()Strip null values
Strip null values from the response.
- Requires PostgREST 11.2.0 or later.
- Cannot be combined with
.csv(). The call throws aPostgrestErrorof kind.invalidRequestbefore it sends a request.
struct Character: Decodable { let id: Int let name: String let nickname: String?}let characters: [Character] = try await supabase .from("characters") .select() .stripNulls() .execute() .valueUsing explain
For debugging slow queries, you can get the Postgres EXPLAIN execution plan of a query using the explain() method. This works on any query, even for rpc() or writes.
Explain is not enabled by default as it can reveal sensitive information about your database. It's best to only enable this for testing environments but if you wish to enable it for production you can provide additional protection by using a pre-request function.
Follow the Performance Debugging Guide to enable the functionality on your project.
- The
formatparameter takes anExplainFormatvalue:.text(the default, human-readable) or.json(machine-readable). - Read the plan with
string()on the response.
try await supabase .from("instruments") .select() .explain() .execute() .string()Test a mutation without committing it
Executes the mutation but rolls back the transaction instead of committing it, so its changes in the transaction are not persisted.
- The mutation runs and its result (including the changes made by triggers) is returned in the response, but the transaction is rolled back afterward.
- The rollback does not undo effects outside the transaction. For example, values taken from a sequence stay used, so an identity column skips them.
- Useful for testing mutations without touching real data.
- Requires PostgREST's
db-tx-endsetting to allow client-controlled transaction rollback.
try await supabase .from("todos") .update(["done": true]) .eq("id", value: 1) .select() .dryRun() .execute()// Row is not actually updated in the database.Overview
The auth methods can be accessed via the supabase.auth namespace.
AuthClient is a Sendable class, not an actor. It reads the stored session asynchronously after the client is created. Until then, status is .loading and currentSession is nil. Call await supabase.auth.initialization() before you read currentSession at launch.
Handling deep links
Flows that leave the app, such as magic links, email confirmations, password resets, and OAuth links that you open yourself, return with a URL. Pass that URL to handleRedirect(_:). It returns nil for a URL that is not an auth redirect. A URL is an auth redirect only when it opens the configured redirectTo or the redirectTo of a pending flow, so set redirectTo on the client configuration.
signInWithOAuth, signInWithSSO, and linkIdentity show the provider page and finish the flow themselves. You do not need to handle their URLs.
UIKit app lifecycle
func application( _ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any]) -> Bool { Task { try await supabase.handleRedirect(url) } return true}UIKit app lifecycle with scenes
In your SceneDelegate.swift:
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) { guard let url = URLContexts.first?.url else { return } Task { try await supabase.handleRedirect(url) }}SwiftUI app lifecycle
On the root view of your scene:
SomeView() .onOpenURL { url in Task { try await supabase.handleRedirect(url) } }When the app also opens other deep links, check the URL first with await supabase.auth.isAuthRedirect(url).
let supabase = try SupabaseClient( supabaseURL: URL(string: "https://xyzcompany.supabase.co")!, supabaseKey: "your-publishable-key", configuration: .init( auth: .init(redirectTo: URL(string: "my-app-scheme://callback")!) ))let auth = supabase.authCreate a new user
- By default, the user needs to verify their email address before logging in. To turn this off, disable Confirm email in your project.
- Confirm email determines if users need to confirm their email address after signing up.
- If Confirm email is enabled, the method returns
.confirmationRequired(user). - If Confirm email is disabled, the method returns
.signedIn(session), stores the session, and emits.signedIn.
- If Confirm email is enabled, the method returns
- The result also has
userandsessionproperties.sessionisnilwhen the user must confirm first. - When the user confirms their email address, they are redirected to the
SITE_URLby default. You can modify yourSITE_URLor add additional redirect URLs in your project. - 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, the method returns
.confirmationRequiredwith an obfuscated/fake user object that has an emptyidentitieslist. - When either Confirm email or Confirm phone (even when phone provider is disabled) is disabled, the error message,
User already registeredis returned.
- When both Confirm email and Confirm phone (even when phone provider is disabled) are enabled in your project, the method returns
- To fetch the currently signed-in user, use
user().
Parameters
- emailOptionalString
One of
emailorphonemust be provided. - phoneOptionalString
One of
emailorphonemust be provided. - passwordString
- optionsOptionalSignUpOptions
The user metadata (
userMetadata, aJSONObject), the redirect URL embedded in the email link (redirectTo, email sign-up only), the messaging channel (channel, phone sign-up only), and the captcha token (captchaToken).
let result = try await supabase.auth.signUp( email: "example@email.com", password: "example-password")switch result {case .signedIn(let session): print("Signed in as \(session.user.id)")case .confirmationRequired(let user): print("Check your inbox, \(user.email ?? "")")}Listen to auth events
- Returns an
AsyncStream<AuthChange>of important events occurring on the user's session. Each call returns a new stream. - The stream is registered when the call returns, so it misses no change. It finishes when your task is canceled or the client is released.
- Each
AuthChangehasevent,session,status(anAuthStatus), andsignOutReason. - Events are delivered asynchronously. To read the state right after a call, use
supabase.auth.statusorsupabase.auth.currentSession. - Emitted events:
initialSession- Emitted right after the client reads the initial session from storage.
- The session can be expired. With
autoRefresh: .automatic, the client tries one refresh of an expired session first, for at mostinitialRefreshTimeout(5 seconds by default). Checksession.isExpired()in your handler.
signedIn- Emitted each time a user session is confirmed or re-established, including on user sign in.
- Avoid making assumptions as to when this event is fired, this may occur even when the user is already signed in. Instead, check the user object attached to the event to see if a new user has signed in and update your application's UI.
signedOut- Emitted when the user signs out. This can be after:
- A call to
supabase.auth.signOut(). - After the user's session has expired for any reason:
- User has signed out on another device.
- The session has reached its timebox limit or inactivity timeout.
- User has signed in on another device with single session per user enabled.
- Check the User Sessions docs for more information.
- A call to
signOutReasontells.userInitiatedapart from.sessionExpired,.sessionRevoked, and.sessionMissing.- Use this to clean up any local storage your application has associated with the user.
- Emitted when the user signs out. This can be after:
tokenRefreshed- Emitted each time a new access and refresh token are fetched for the signed-in user.
- With auto refresh, the client refreshes the session before the access token expires. The token in the event can still be expired when your handler runs, for example after the app resumes. When you need a session for a new request, call
try await supabase.auth.session(). - The frequency of this event is related to the JWT expiry limit configured on your project.
userUpdated- Emitted each time
updateUser(_:redirectTo:)orlinkIdentityfinishes successfully, afterunlinkIdentity(_:)when the client can fetch the updated user, and when the signed-in user verifies an email or phone change. Listen to it to update your application's UI based on new profile information.
- Emitted each time
passwordRecovery- Emitted instead of the
signedInevent when the user opens a password recovery link, or verifies a code withverifyOTPand type.recovery. - Use it to show a UI to the user where they can reset their password.
- Emitted instead of the
mfaChallengeVerified- Emitted when the user verifies an MFA challenge.
for await change in supabase.auth.events() { print(change.event, change.session?.user.id as Any)}Create an anonymous user
- Returns the session of a new 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
captchaTokenparam.
let session = try await supabase.auth.signInAnonymously(captchaToken: captchaToken)Sign in a user
- Requires either an email and password or a phone number and password.
- Returns the new session, stores it, and emits
.signedIn.
Parameters
- emailOptionalString
One of
emailorphonemust be provided. - phoneOptionalString
One of
emailorphonemust be provided. - passwordString
- captchaTokenOptionalString
try await supabase.auth.signIn( email: "example@email.com", password: "example-password")Sign in with ID token (native sign-in)
- Signs in with an ID token that a third-party identity provider issued, such as Sign in with Apple or Google Sign-In. The server checks the token and creates the user if needed.
- Generate a
Noncefor each attempt. Sendnonce.hashedto the provider and passnonce.rawto the server.
let nonce = Nonce.generate()// Pass nonce.hashed to the provider, for example as request.nonce// in SignInWithAppleButton.let session = try await supabase.auth.signInWithIDToken( IDTokenCredentials( provider: .apple, idToken: "your-id-token", nonce: nonce.raw ))Sign in a user through OTP
- Requires either an email or phone number.
- This method is used for passwordless sign-ins where a OTP is sent to the user's email or phone number.
- If the user doesn't exist,
signInWithOTP()will signup the user instead. To restrict this behavior, setshouldCreateUsertofalsein the options. - If you're using an email, you can configure whether you want the user to receive a magiclink or a OTP.
- If you're using phone, you can configure whether you want the user to receive a OTP.
- Pass a code to
verifyOTP(). Pass the URL that a magic link opens tohandleRedirect(_:). - For a phone, the method returns the
MessageID?that the SMS provider gave the message. - The magic link's destination URL is determined by the
SITE_URL. - See redirect URLs and wildcards to add additional redirect URLs to your project.
- Magic links and OTPs share the same implementation. To send users a one-time code instead of a magic link, modify the magic link email template to include
{{ .Token }}instead of{{ .ConfirmationURL }}. - See our Twilio Phone Auth Guide for details about configuring WhatsApp sign in.
Parameters
- emailOptionalString
One of
emailorphonemust be provided. - phoneOptionalString
One of
emailorphonemust be provided. - optionsOptionalEmailOTPOptions | PhoneOTPOptions
EmailOTPOptionsfor an email:shouldCreateUser,userMetadata,redirectTo(the redirect URL embedded in the email link), andcaptchaToken.PhoneOTPOptionsfor a phone:shouldCreateUser,userMetadata,channel(.smsor.whatsapp), andcaptchaToken. WhenshouldCreateUserorchannelisnil, the server applies its default: it creates the user, and it sends the code by SMS.
try await supabase.auth.signInWithOTP( email: "example@email.com", options: EmailOTPOptions( redirectTo: URL(string: "my-app-scheme://callback")! ))Sign in a user through OAuth
- This method is used for signing in using a third-party provider.
- Supabase supports many different third-party providers.
- The client starts a PKCE flow, shows the provider page, exchanges the code from the callback URL, stores the session, and emits
.signedIn. - The method needs a redirect URL: pass
redirectToin the options or set it on the client configuration. The URL must be in your project's redirect URLs. - A user who cancels gets a
CancellationError.
Parameters
- providerProvider
The third-party provider. The first argument, without a label.
- optionsOptionalOAuthOptions
scopes(an array of scopes to request),redirectTo(a URL to send the user to after they are confirmed), andqueryItems(additional query items). - presenterOptionalWebAuthPresenter
Shows the provider page and returns the callback URL. The default on Apple platforms is
ASWebAuthenticationSessionPresenter. On other platforms you must pass one.
let session = try await supabase.auth.signInWithOAuth( .github, options: OAuthOptions(redirectTo: URL(string: "my-app-scheme://callback")!), presenter: ASWebAuthenticationSessionPresenter(prefersEphemeralWebBrowserSession: true))Sign in a user through SSO
- Before you can call this method you need to establish a connection to an identity provider. Use the CLI commands to do this.
- The client shows the identity provider page, exchanges the code, stores the session, and emits
.signedIn. - If you've associated an email domain to the identity provider, you can use
.domainto start a sign-in flow. - In case you need to use a different way to start the authentication flow with an identity provider, you can use
.providerID. For example:- Mapping specific user email addresses with an identity provider.
- Using different hints to identity the identity provider to be used by the user, like a company-specific page, IP address or other tracking information.
- To show the page yourself, use
ssoSignInURL(_:options:). It returns anOAuthFlowwith the URL to open.
Parameters
- targetSSOTarget
.domain(String), the domain name of the organization to use SSO with, or.providerID(UUID), the UUID of the SSO provider. - optionsOptionalSSOOptions
redirectTo, the URL to redirect the user to after they have signed in, which must be a configured redirect URL for your Supabase instance, andcaptchaToken. - presenterOptionalWebAuthPresenter
Shows the identity provider page. The default on Apple platforms is
ASWebAuthenticationSessionPresenter. On other platforms you must pass one.
// You can extract the user's email domain and use it to trigger the// authentication flow with the correct identity provider.let session = try await supabase.auth.signInWithSSO( .domain("company.com"), options: SSOOptions(redirectTo: URL(string: "my-app-scheme://callback")!))Sign in a user through Web3 (Solana, Ethereum)
Signs in a user via a signed Sign in with Ethereum (EIP-4361) or Sign in with Solana message.
- Supports Ethereum (Sign-In with Ethereum) and Solana (Sign-In with Solana), both of which derive from the EIP-4361 standard.
- Your app is responsible for building the message and obtaining the signature from the user's wallet (e.g. via a WalletConnect session or native wallet SDK) before calling this method.
- For
Web3Chain.ethereumthe signature is a0x-prefixed hex encoded string. ForWeb3Chain.solanait is a base64 encoded string. - Pass a captcha token with
Web3Credentials(captchaToken:).
let session = try await supabase.auth.signInWithWeb3( Web3Credentials( chain: .ethereum, message: siweMessage, signature: signatureHex ))Sign in with a passkey
Signs the user in with a passkey (WebAuthn). Available on Apple platforms except watchOS.
- Drives the full WebAuthn ceremony end to end: fetches assertion options from the server, presents the native passkey UI via
AuthenticationServices, and verifies the assertion. - Does not require an existing session. On success the session is persisted and a
signedInauth change event is emitted. anchoris the window to show the sheet from.niluses the app's key window. An app extension has no key window, so pass one there.- A user who dismisses the sheet gets a
CancellationError. - For lower-level control, use
passkeys.authenticationOptions()+passkeys.verifyAuthentication(challengeID:credential:)instead. - The app's Associated Domains entitlement must list
webcredentials:<rpID>. - Passkey support is experimental. Opt in with
@_spi(Experimental) import Supabase. The API may change in future releases. - Passkeys must be enabled for your project in the Dashboard under Authentication → Passkeys.
// Must opt in: @_spi(Experimental) import Supabaselet session = try await supabase.auth.passkeys.signIn()let user = session.userRegister a passkey
Registers a new passkey (WebAuthn credential) for the signed-in user. Available on Apple platforms except watchOS.
- Drives the full WebAuthn ceremony end to end: fetches creation options from the server, presents the native passkey registration UI, and stores the credential.
- Requires an authenticated, non-anonymous user.
- Returns the stored passkey as a
PasskeyListItem. The server names the passkey after the authenticator. Change the name withpasskeys.rename(id:friendlyName:). anchoris the window to show the sheet from.niluses the app's key window.- For lower-level control, use
passkeys.registrationOptions()+passkeys.verifyRegistration(challengeID:credential:)instead. - Passkey support is experimental. Opt in with
@_spi(Experimental) import Supabase.
// Must opt in: @_spi(Experimental) import Supabaselet passkey = try await supabase.auth.passkeys.register()print("Registered passkey \(passkey.id)")Get user claims from verified JWT
- Verifies a JWT and extracts its claims. Returns
VerifiedClaims, with typed properties such assubject,email,role,sessionID, andexpiresAt. claims()verifies the access token of the current session, and refreshes an expired session first.claims(jwt:)verifies the token you pass.- A token signed with an asymmetric key (such as ES256 or RS256) that names its key in the
kidheader is verified on the device against the project's JSON Web Key Set. - The Auth server verifies every other token through
user(jwt:): a token signed with a symmetric key (HS256), a token without akid, and a token whose key the client cannot find. - Each client caches the JSON Web Key Set for 10 minutes. A token whose key is not in the cache triggers a new fetch, so rotated keys resolve at once.
- A token without an
exporsubclaim fails verification. The anon key and the service role key have nosub, soclaims(jwt:)rejects them.
Parameters
- jwtOptionalString
The JWT to verify. Use
claims(options:)to verify the access token from the current session. - optionsOptionalClaimsOptions
Options for JWT verification. Can specify
allowsExpiredto skip expiration check andjwksto provide custom JSON Web Key Set.
let claims = try await supabase.auth.claims()print("User ID: \(claims.subject)")print("Email: \(claims.email ?? "N/A")")print("Role: \(claims.role ?? "N/A")")Sign out a user
- The default scope is
.local. It signs out this device only. The user's sessions on other devices stay. .localremoves the session, clears pending PKCE flows, and emits.signedOutbefore the request, so the device is signed out whatever the server answers..globalends every session of the user. The client removes the local session only after the server ended them. When the request fails, the session stays and the method throws..othersends every other session of the user and keeps this one. It throws an error of kind.sessionMissingwhen no session is stored.- With no stored session,
.localand.globalstill emit.signedOut.
try await supabase.auth.signOut()Send a password reset request
- Sends a password reset email. The email holds a link, or a code when the template uses
{{ .Token }}. - Pass the URL that the link opens to
handleRedirect(_:). It returns.signedIn(_, verification: .recovery). - Or pass the code to
verifyOTP(email:token:type:)with type.recovery. - Both sign the user in and emit
.passwordRecovery. Then set the new password withupdateUser(_:redirectTo:). - The call succeeds for an unknown email too, so it does not show which addresses have an account.
Parameters
- emailString
- optionsOptionalResetPasswordOptions
redirectTo, the URL that the reset link opens, andcaptchaToken.
try await supabase.auth.resetPassword( email: "example@email.com", options: ResetPasswordOptions( redirectTo: URL(string: "my-app-scheme://callback")! ))Verify and log in through OTP
- The
verifyOTPmethod takes in different verification types. If a phone number is used, the type can either be.smsor.phoneChange. If an email address or a token hash is used, the type can be one of the following:.signup,.magiclink,.recovery,.invite,.emailChange, or.email. - The verification type used should be determined based on the corresponding auth method called before
verifyOTPto sign up / sign-in a user. verifyOTP(phone:token:type:)returns theSession.verifyOTP(email:token:type:)andverifyOTP(tokenHash:type:)return aVerifyOTPResult:.signedIn(session), or.emailChangePending(message:)for the first confirmation of a secure email change.- The event follows the type:
.passwordRecoveryfor.recovery,.userUpdatedfor an email or phone change of the signed-in user, and.signedInotherwise. - The call signs in the account that owns the code and replaces the current session. When a user is signed in already, ask them to confirm first.
Parameters
- emailOptionalString
One of
phone,email, ortokenHashmust be provided. - phoneOptionalString
One of
phone,email, ortokenHashmust be provided. - tokenHashOptionalString
The token hash from the user's email link. One of
phone,email, ortokenHashmust be provided. - typeEmailOTPType | PhoneOTPType
- tokenOptionalString
The OTP sent to the user. Required if using
phoneoremail.
let session = try await supabase.auth.verifyOTP( phone: "+13334445555", token: "123456", type: .sms)Retrieve a session
- Returns the session, refreshing it first when its access token expires in less than 30 seconds.
- Throws an
AuthErrorof kind.sessionMissingwhen no session is stored, and of kind.sessionInvalidatedwhen the server rejects the refresh of an expired session. - With
autoRefresh: .disabled, it throws an error of kind.refreshDisabledwhen the session is expired.
let session = try await supabase.auth.session()Retrieve a new session
- This method will refresh the stored session whether the current one is expired or not.
- When a concurrent refresh or sign-in already replaced the session with a valid one, it returns that session without a request.
- The client runs one refresh at a time. When a refresh fails, a new refresh with the same token in the next 60 seconds throws the same error without a request.
- A rejected refresh does not sign out while the access token is still valid. Wait for the
.signedOutevent instead of treating the error as a sign-out. - To sign in with a refresh token from elsewhere, use
importSession(accessToken:refreshToken:).
let session = try await supabase.auth.refreshSession()Retrieve a user
- This method validates the user's access token JWT on the server and returns the authenticated user. It does not check what the user can do. Your RLS policies and endpoints do that.
- Fetches the user object from the database instead of local session.
- Should be used only when you require the most current user data. For faster results,
currentUseris recommended. user()sends the access token of the current session and refreshes it first when it has expired.user(jwt:)sends the token you pass as is.
let user = try await supabase.auth.user()Update a user
- In order to use the
updateUser()method, the user needs to be signed in first. - Returns the updated
User, merges it into the current session, and emits.userUpdated. - By default, email updates sends a confirmation link to both the user's current and new email. To only send a confirmation link to the user's new email, disable Secure email change in your project's email auth provider settings.
- An email change starts a PKCE flow. Pass the URL that the confirmation link opens to
handleRedirect(_:). - The SDK sends the keys of
userMetadataas you wrote them. It does not convert them to snake_case.
try await supabase.auth.updateUser( UpdateUser(email: "new@email.com"), redirectTo: URL(string: "my-app-scheme://callback")!)Retrieve identities linked to a user
- The user needs to be signed in to call
identities(). - The method fetches the user from the server and returns its identities.
UserIdentity.idis the Supabase identity UUID (identity_idin JSON). The user's ID at the provider isproviderUserID.
let identities = try await supabase.auth.identities()Link an identity to a user
- The Enable Manual Linking option must be enabled from your project's authentication settings.
- The user needs to be signed in to call
linkIdentity(). - If the candidate identity is already linked to the existing user or another user,
linkIdentity()will fail. - The client shows the provider page with a presenter, exchanges the code, stores the new session, and emits
.userUpdated. It returns the newSession. - To show the page yourself, use
linkIdentityURL(_:options:). It returns anOAuthFlowwith the URL to open.
let session = try await supabase.auth.linkIdentity( .google, options: OAuthOptions(redirectTo: URL(string: "my-app-scheme://callback")!))Unlink an identity from a user
- The Enable Manual Linking option must be enabled from your project's authentication settings.
- The user needs to be signed in to call
unlinkIdentity(). - The user must have at least 2 identities in order to unlink an identity.
- The identity to be unlinked must belong to the user.
- After the unlink, the client fetches the user from the server, stores it in
currentUser, and emits.userUpdated. - If that fetch fails, the unlink still succeeds, but
currentUserkeeps the old identities and no.userUpdatedis emitted. Calluser()to read the identities again. Do not retry the unlink.
// retrieve all identities linked to a userlet identities = try await supabase.auth.identities()// find the google identityif let googleIdentity = identities.first(where: { $0.provider == .google }) { // unlink the google identity try await supabase.auth.unlinkIdentity(googleIdentity)}Send a password reauthentication nonce
- This method is used together with
updateUser(_:redirectTo:)when a user's password needs to be updated. - If you require your user to reauthenticate before updating their password, you need to enable the Secure password change option in your project's email provider settings.
- A user is only require to reauthenticate before updating their password if Secure password change is enabled and the user hasn't recently signed in. A user is deemed recently signed in if the session was created in the last 24 hours.
- This method will send a nonce to the user's email. If the user doesn't have a confirmed email address, the method will send the nonce to the user's confirmed phone number instead.
- Pass the nonce as
UpdateUser(nonce:).
try await supabase.auth.reauthenticate()Resend an OTP
- Resends a signup confirmation, email change, or phone change email to the user.
- Passwordless sign-ins can be resent by calling the
signInWithOTP()method again. - Password recovery emails can be resent by calling the
resetPassword(email:options:)method again. - This method only resends an email or phone OTP to the user if there an initial signup, email change, or phone change request was made.
- You can specify a redirect URL when you resend an email link with
ResendEmailOptions(redirectTo:). - The phone variant returns the
MessageID?that the SMS provider gave the message.
try await supabase.auth.resend( email: "email@example.com", type: .signup, options: ResendEmailOptions( redirectTo: URL(string: "my-app-scheme://callback")! ))Set the session data
importSession()signs in with a session your app got outside this client, such as tokens that a tvOS app receives from a sign-in on another device.- The client reads the expiry from the access token. When the token has expired, it uses the refresh token to get a new session. Otherwise it fetches the user with the access token.
- The client stores the session and emits
.signedInonce. When a request fails, the stored session stays as it was. - The refresh token can only be used once to obtain a new session.
- Refresh token rotation is enabled by default on all projects to guard against replay attacks.
- You can configure the
REFRESH_TOKEN_REUSE_INTERVALwhich provides a short window in which the same refresh token can be used multiple times in the event of concurrency or offline issues.
let session = try await supabase.auth.importSession( accessToken: "access_token", refreshToken: "refresh_token")Exchange an auth code for a session
- The client always uses PKCE for the flows it starts, so their redirect URLs carry a code.
- Prefer
handleRedirect(_:), which reads the code from the URL and handles the same URL only once. Use this method when you read the code yourself. - It needs a pending flow for the code. With no stored flow, it throws an error of kind
.oauthFlowFailedwithout a request. - Pass the
idof theOAuthFlowfromoauthSignInURL,linkIdentityURL, orssoSignInURLasflowID. Without it, as for the code in an email link, the client tries the pending flows newest first.
let session = try await supabase.auth.exchangeCodeForSession( "34e770dd-9ff9-416c-87fa-43b31d7ef225", flowID: flow.id)Start auto-refresh session (non-browser)
Resumes the automatic session refresh process after stopAutoRefresh().
- With
autoRefresh: .automatic, the default, auto refresh starts when the client is created, on every platform. Call this method only afterstopAutoRefresh(). - Under
.manualand.disabled, this method does nothing. - The client refreshes the session 90 seconds before the access token expires, and retries a failed refresh with a capped exponential backoff.
- On iOS, iPadOS, tvOS, visionOS, Mac Catalyst, and watchOS, auto refresh pauses while the app is in the background and resumes when it returns to the foreground.
- Calls to this method and to
stopAutoRefresh()take effect in order. Each returns once its call took effect.
await supabase.auth.startAutoRefresh()Stop auto-refresh session (non-browser)
Stops the automatic session refresh process until the next startAutoRefresh().
- A return to the foreground does not resume auto refresh after this call.
- To turn off auto refresh from the start, set
autoRefresh: .manualor.disabledin the client configuration. Use.disabledin an app extension that shares the session with its app.
await supabase.auth.stopAutoRefresh()Initialize client session
- Returns once the client has read the stored session, so
statusis no longer.loading. - The client reads storage asynchronously after it is created. Until then,
currentSessionisnil. Call this method before you readcurrentSessionorcurrentUserat launch. - When the client refreshes an expired stored session first, this method waits for that refresh too, for at most
initialRefreshTimeout. - While storage cannot be read, for example after a launch into the background before the first unlock, this method waits until it can. It returns early when the calling task is canceled.
await supabase.auth.initialization()if let session = supabase.auth.currentSession { print("Signed in as \(session.user.id)")}Auth MFA
This section contains methods for Multi-Factor Authentication (MFA). They live in the supabase.auth.mfa namespace.
TOTP (time-based one-time password) and phone are the stable second factors. WebAuthn (passkey) as a second factor is experimental. Opt in with @_spi(Experimental) import Supabase. The first-factor passkey API lives in supabase.auth.passkeys. See the Auth Passkey section.
A user can enroll more than one factor, with an upper limit of 10. A second TOTP factor is a good backup. The server can also issue single-use recovery codes. See mfa.recoveryCodes.generate().
Factor and challenge IDs are UUID values. "\(factor.id)" prints in uppercase, so compare UUID values, not strings. FactorType and AuthenticatorAssuranceLevel are structs. Use .rawValue to get the string.
Enroll a factor
- Each factor type has its own method:
enrollTOTP(issuer:friendlyName:)andenrollPhone(_:friendlyName:). Each returns the data for that factor type. - The new factor is
unverified. Use itsidto create a challenge. - To create a challenge, see
mfa.challenge(). - To verify a challenge, see
mfa.verify(). - To create and verify a challenge in a single step, see
mfa.challengeAndVerify(). - For WebAuthn,
mfa.enrollWebAuthn(friendlyName:anchor:)runs the full ceremony and returns the upgraded session (experimental). It is not available on watchOS.
let enrollment = try await supabase.auth.mfa.enrollTOTP( issuer: "optional issuer", friendlyName: "optional friendly name")// Use the id to create a challenge.// The challenge can be verified by entering the code generated from the authenticator app.// The code will be generated upon scanning the qrCode or entering the secret into the authenticator app.let id = enrollment.idlet qrCode = enrollment.qrCodelet secret = enrollment.secretlet uri = enrollment.uriCreate a challenge
- An enrolled factor is required before creating a challenge.
- For a phone factor, this call sends the code. Pass
channel: .whatsappto send it through WhatsApp. The server default is SMS. - To verify a challenge, see
mfa.verify(). expiresAtis aDate.
let challenge = try await supabase.auth.mfa.challenge( factorID: UUID(uuidString: "34e770dd-9ff9-416c-87fa-43b31d7ef225")!)let challengeID = challenge.idlet expiresAt = challenge.expiresAtVerify a challenge
- To verify a challenge, please create a challenge first.
- On success, the client stores the upgraded
aal2session, signs out the user's other sessions, and emits.mfaChallengeVerified. Verifying anunverifiedfactor also marks itverified. - For WebAuthn factors,
mfa.verifyWebAuthn(factorID:anchor:)runs the challenge, the passkey sheet, and the verification in one call (experimental). It only works with a verified factor. It is not available on watchOS.
let session = try await supabase.auth.mfa.verify( factorID: UUID(uuidString: "34e770dd-9ff9-416c-87fa-43b31d7ef225")!, challengeID: UUID(uuidString: "4034ae6f-a8ce-4fb5-8ee5-69a5863a7c15")!, code: "123456")Create and verify a challenge
- An enrolled factor is required before invoking
challengeAndVerify(). - Executes
mfa.challenge()andmfa.verify()in a single step. - Use it for TOTP factors, where the user already has the code. For a phone factor, call
challenge(factorID:channel:)first so the server sends the code.
let session = try await supabase.auth.mfa.challengeAndVerify( factorID: UUID(uuidString: "34e770dd-9ff9-416c-87fa-43b31d7ef225")!, code: "123456")Unenroll a factor
- The session must be at
aal2to remove averifiedfactor. - To remove the recovery codes factor, use
mfa.recoveryCodes.unenroll().
let response = try await supabase.auth.mfa.unenroll( factorID: UUID(uuidString: "34e770dd-9ff9-416c-87fa-43b31d7ef225")!)print(response.id) // ID of the unenrolled factorGet Authenticator Assurance Level
- Authenticator Assurance Level (AAL) is the measure of the strength of an authentication mechanism.
- In Supabase, having an AAL of
aal1refers to having the 1st factor of authentication such as an email and password or OAuth sign-in whileaal2refers to the 2nd factor of authentication such as a time-based, one-time-password (TOTP). - If the user has a verified factor, the
nextLevelfield will returnaal2, else, it will return the current level. - The method fetches the user from the server, so
nextLevelincludes factors enrolled on other devices. - With no session, it throws an
AuthErrorof kind.sessionMissing.
let aal = try await supabase.auth.mfa.assuranceLevel()let currentLevel = aal.currentLevellet nextLevel = aal.nextLevellet currentAuthenticationMethods = aal.currentAuthenticationMethodsList all factors for current user
- The method fetches the user from the server on each call, so it includes factors enrolled on other devices.
- It splits the factors by status in
verifiedandunverified.allreturns both. Filter onfactorTypefor one type. verifiedincludes the recovery codes factor, which cannot be challenged.
let factors = try await supabase.auth.mfa.factors()let verified = factors.verifiedlet unverified = factors.unverifiedGetRecoveryCodesStatusAsync()
- Returns how many codes the current set holds and how many are unused. It never returns the codes.
- Works at any assurance level. When
remainingreaches zero, ask the user to regenerate the codes. - Throws an error with code
mfa_factor_not_foundwhen the user has no recovery codes. - Recovery codes are an experimental Supabase Auth feature. Enable them on the Auth server first.
let status = try await supabase.auth.mfa.recoveryCodes.status()print("\(status.remaining) of \(status.total) codes left")GenerateRecoveryCodesAsync()
- The session must be at
aal2, and the user must already have another verified factor. - The codes are returned only once. Show them to the user and ask them to store the codes safely.
- A user has one set of recovery codes. To replace it, use
mfa.recoveryCodes.regenerate(). - Recovery codes are an experimental Supabase Auth feature. Enable them on the Auth server first.
let generated = try await supabase.auth.mfa.recoveryCodes.generate( friendlyName: "Backup codes")// Show generated.codes to the user once.let codes = generated.codesRegenerateRecoveryCodesAsync()
- Replaces the user's recovery codes with a new set. The old codes stop working at once.
- The session must be at
aal2. - Throws an error with code
mfa_factor_not_foundwhen the user has no recovery codes. Usegenerate(friendlyName:)instead.
let regenerated = try await supabase.auth.mfa.recoveryCodes.regenerate()let codes = regenerated.codesVerifyRecoveryCodeAsync()
- Verifies one recovery code and upgrades the session to
aal2. Each code works only once. - On success, the client stores the upgraded session, signs out the user's other
aal1sessions, and emits.mfaChallengeVerified. - The server ignores letter case, whitespace, and
-separators.
let session = try await supabase.auth.mfa.recoveryCodes.verify( code: "K4M9-X7QP-2AB8-HT3Z")UnenrollRecoveryCodesAsync()
- Removes the recovery codes factor and every code in it.
- The session must be at
aal2.
let response = try await supabase.auth.mfa.recoveryCodes.unenroll()print(response.id) // ID of the removed factorAuth Passkey
Lower-level passkey methods for custom authenticator flows and platforms where AuthenticationServices is unavailable (watchOS). They live in the supabase.auth.passkeys namespace.
These methods handle the network side of the WebAuthn ceremony only. You drive the platform authenticator between fetching options and submitting the credential. For an end-to-end flow, prefer passkeys.signIn(anchor:) and passkeys.register(anchor:).
Passkey support is experimental. Opt in with @_spi(Experimental) import Supabase. The API may change in any release.
List passkeys
Returns the list of passkeys registered to the signed-in user.
// @_spi(Experimental) import Supabaselet passkeys: [PasskeyListItem] = try await supabase.auth.passkeys.list()Update a passkey
Updates the friendly name of a passkey. Limited to 120 characters.
Parameters
- idRequiredUUID
ID of the passkey to rename.
- friendlyNameRequiredString
New human readable name. Limited to 120 characters.
// @_spi(Experimental) import Supabaselet passkey = try await supabase.auth.passkeys.rename( id: UUID(uuidString: "34e770dd-9ff9-416c-87fa-43b31d7ef225")!, friendlyName: "Work laptop")Delete a passkey
Removes a passkey from the signed-in user's account.
Parameters
- idRequiredUUID
ID of the passkey to delete.
// @_spi(Experimental) import Supabasetry await supabase.auth.passkeys.delete( id: UUID(uuidString: "34e770dd-9ff9-416c-87fa-43b31d7ef225")!)Start passkey registration
Fetches credential creation options to register a new passkey for the signed-in user.
- Pass the returned
options(W3CPublicKeyCredentialCreationOptions) to the platform authenticator. - After running the authenticator, submit the result with
passkeys.verifyRegistration(challengeID:credential:). challengeIDis aUUIDandexpiresAtis aDate.
// @_spi(Experimental) import Supabaselet options: PasskeyRegistrationOptions = try await supabase.auth.passkeys.registrationOptions()// Hand options.options to the platform authenticator.Verify passkey registration
Stores a newly created passkey for the signed-in user. The server names the passkey after the authenticator. Change the name with passkeys.rename(id:friendlyName:).
Parameters
- challengeIDRequiredUUID
The
challengeIDreturned bypasskeys.registrationOptions(). - credentialRequiredJSONValue
The W3C
PublicKeyCredentialJSON produced by the authenticator.
// @_spi(Experimental) import Supabaselet passkey: PasskeyListItem = try await supabase.auth.passkeys.verifyRegistration( challengeID: options.challengeID, credential: credential)Start passkey authentication
Fetches assertion options to authenticate with a passkey.
- Does not require an existing session.
- Pass the returned
options(W3CPublicKeyCredentialRequestOptions) to the platform authenticator. - After running the authenticator, submit the result with
passkeys.verifyAuthentication(challengeID:credential:).
// @_spi(Experimental) import Supabaselet options: PasskeyAuthenticationOptions = try await supabase.auth.passkeys.authenticationOptions()// Hand options.options to the platform authenticator.Verify passkey authentication
Verifies a passkey assertion and establishes a session at aal1. On success the session is stored and a .signedIn auth event is emitted. It returns the Session.
Parameters
- challengeIDRequiredUUID
The
challengeIDreturned bypasskeys.authenticationOptions(). - credentialRequiredJSONValue
The W3C
PublicKeyCredentialJSON produced by the authenticator.
// @_spi(Experimental) import Supabaselet session: Session = try await supabase.auth.passkeys.verifyAuthentication( challengeID: options.challengeID, credential: credential)let user = session.userAuth Admin
- Admin methods live on
AuthAdminClient, a separate client.supabase.auth.admindoes not exist in v3. AuthAdminClientrequires asecretkey. It sends the key on every request and never reads or writes a user session.- These methods are considered admin methods and should be called on a trusted server. Never expose your
secretkey in a browser or mobile app. - Unlike the other clients, the
AuthAdminClientinitializer does not throw.
import Supabaselet admin = AuthAdminClient( configuration: .init( url: supabaseURL.appendingPathComponent("auth/v1"), secretKey: secretKey ))Retrieve a user
Get user by ID.
- The
user(id:)method requires a user's ID.
let user = try await admin.user( id: UUID(uuidString: "715ed5db-f090-4b8c-a067-640ecee36aa0")!)List all users
List all users in the system.
listUsers(page:pageSize:)returns oneUserPage. Pages start at1.- To walk every page, iterate
users(pageSize:). It fetches each page as you go.
let page = try await admin.listUsers()let users = page.usersCreate a user
Create a new user.
- The server sends no confirmation email. Set
confirmsEmailorconfirmsPhonetotrueto mark the address as confirmed. - To email the user an invite instead, use
inviteUser(email:userMetadata:redirectTo:).
let user = try await admin.createUser( AdminCreateUser( email: "user@email.com", password: "password", confirmsEmail: true ))Delete a user
- The
deleteUser()method requires the user's ID, which maps to theauth.users.idcolumn. - Pass
softDelete: trueto disable the account and keep its data. With nosoftDelete, the server removes the user.
try await admin.deleteUser( id: UUID(uuidString: "715ed5db-f090-4b8c-a067-640ecee36aa0")!)Send an email invite link
Send an invite link to the user's email address.
userMetadatais stored in the user'suser_metadata.- The admin client has no default redirect. Without
redirectTo, the server uses the site URL.
let user = try await admin.inviteUser( email: "user@email.com", userMetadata: ["role": "admin"], redirectTo: URL(string: "https://example.com/welcome"))Generate an email link
Generates an email link for a specific action without sending it. This is useful for custom admin functionality where you want to build the email or OTP flow yourself.
GenerateLinkexposes a static factory for each link type:.signUp(email:password:userMetadata:redirectTo:),.invite(email:userMetadata:redirectTo:),.magicLink(email:userMetadata:redirectTo:),.recovery(email:redirectTo:),.emailChangeCurrent(email:newEmail:redirectTo:), and.emailChangeNew(email:newEmail:redirectTo:).generateLink()creates the user for.signUpand.inviteif one doesn't already exist.- The admin client has no default redirect. Without
redirectTo, the server uses the site URL.
let response = try await admin.generateLink( .signUp( email: "email@example.com", password: "secret" ))let actionLink = response.properties.actionLinklet emailOTP = response.properties.emailOTPUpdate a user
Update user by ID.
- The server changes only the fields you set in
AdminUpdateUser. banDurationis aDuration. Pass.zeroto lift a ban.
let user = try await admin.updateUser( id: UUID(uuidString: "715ed5db-f090-4b8c-a067-640ecee36aa0")!, AdminUpdateUser( email: "newemail@email.com" ))Sign out a user (admin)
Signs out a specific user by revoking their session(s), using that user's access token (JWT).
- Unlike
supabase.auth.signOut(), this method takes the target user's access token (JWT), not a user ID. - By default,
signOut()uses the.globalscope, which revokes every session for the user. Pass.localto revoke only the session tied to the given JWT, or.othersto keep that session and revoke all the rest.
try await admin.signOut(jwt: jwt)Delete a factor for a user
Delete an MFA factor of a user.
- Requires
secretkey. - The user's sessions drop to
aal1.
try await admin.mfa.deleteFactor( id: UUID(uuidString: "34e770dd-9ff9-416c-87fa-43b31d7ef225")!, forUser: UUID(uuidString: "715ed5db-f090-4b8c-a067-640ecee36aa0")!)List all factors for a user (admin)
List the MFA factors of a user.
- Requires
secretkey.
let factors = try await admin.mfa.listFactors( forUser: UUID(uuidString: "715ed5db-f090-4b8c-a067-640ecee36aa0")!)Passkey Admin
Admin methods to manage the passkeys of any user. They live in the admin.passkeys namespace and require a secret key.
Passkey support is experimental. Opt in with @_spi(Experimental) import Supabase. The API may change in any release.
List passkeys for a user
List the passkeys of a user.
// @_spi(Experimental) import Supabaselet passkeys = try await admin.passkeys.list( forUser: UUID(uuidString: "715ed5db-f090-4b8c-a067-640ecee36aa0")!)Delete a passkey
Delete a passkey of a user.
// @_spi(Experimental) import Supabasetry await admin.passkeys.delete( id: UUID(uuidString: "34e770dd-9ff9-416c-87fa-43b31d7ef225")!, forUser: UUID(uuidString: "715ed5db-f090-4b8c-a067-640ecee36aa0")!)AdminAuth().CreateCustomProviderAsync()
Create a custom OAuth 2.0 or OIDC provider.
- Requires
secretkey. - Build the settings with
CreateCustomProvider.oauth2(...)orCreateCustomProvider.oidc(...), then set the optional fields. - The identifier must start with
custom:. - For an OIDC provider, the server fetches the discovery document first. The call fails with a
validation_failederror when the document is unreachable or invalid.
let provider = try await admin.customProviders.create( .oidc( identifier: "custom:acme", name: "Acme", clientID: "client-id", clientSecret: "client-secret", issuer: "https://auth.acme.com" ))AdminAuth().GetCustomProviderAsync()
Get a custom provider.
- Requires
secretkey.
let provider = try await admin.customProviders.provider(identifier: "custom:acme")AdminAuth().ListCustomProvidersAsync()
List the custom providers.
- Requires
secretkey. - Pass
type:to list only the providers of one type.
let providers = try await admin.customProviders.list()AdminAuth().UpdateCustomProviderAsync()
Update a custom provider.
- Requires
secretkey. - The server changes only the fields you set in
UpdateCustomProvider. - When the issuer or discovery URL of an OIDC provider changes, the server fetches the discovery document again.
let provider = try await admin.customProviders.update( identifier: "custom:acme", UpdateCustomProvider( name: "Acme Corp", scopes: ["openid", "email", "profile"] ))AdminAuth().DeleteCustomProviderAsync()
Delete a custom provider.
- Requires
secretkey.
try await admin.customProviders.delete(identifier: "custom:acme")OAuth Admin
Admin methods to manage OAuth clients. They live in the admin.oauth namespace and require a secret key.
They are only relevant when the OAuth 2.1 server is enabled in Supabase Auth. Call them only on a server. Never ship your secret key in an app.
List OAuth clients
List all OAuth clients.
- Requires
secretkey. - This method is part of the OAuth 2.1 server administration API.
- Only works when the OAuth 2.1 server is enabled in your Supabase Auth configuration.
- Returns
[OAuthClient], newest first. The server does not page this list.
let clients = try await admin.oauth.listClients()Create OAuth client
Create a new OAuth client.
- Requires
secretkey. - This method is part of the OAuth 2.1 server administration API.
- Only works when the OAuth 2.1 server is enabled in your Supabase Auth configuration.
- The response holds
clientSecret. The server returns it only on create and on regenerate.
Parameters
- clientCreateOAuthClient
The new client, including its name and redirect URIs.
let client = try await admin.oauth.createClient( CreateOAuthClient( clientName: "My OAuth App", redirectURIs: [URL(string: "https://example.com/callback")!] ))let clientID = client.clientIDlet clientSecret = client.clientSecretGet OAuth client
Get details of a specific OAuth client.
- Requires
secretkey. - This method is part of the OAuth 2.1 server administration API.
Parameters
- idUUID
The ID of the OAuth client to retrieve.
let client = try await admin.oauth.client( id: UUID(uuidString: "12345678-1234-1234-1234-123456789012")!)Update OAuth client
Update an OAuth client.
- Requires
secretkey. - This method is part of the OAuth 2.1 server administration API.
- The server changes only the fields you set in
UpdateOAuthClient.redirectURIsandgrantTypesreplace the current lists.
Parameters
- idUUID
The ID of the OAuth client to update.
- changesUpdateOAuthClient
The fields to change.
let client = try await admin.oauth.updateClient( id: UUID(uuidString: "12345678-1234-1234-1234-123456789012")!, UpdateOAuthClient( clientName: "My Renamed App", redirectURIs: [URL(string: "https://example.com/new-callback")!] ))Delete OAuth client
Delete an OAuth client.
- Requires
secretkey. - This method is part of the OAuth 2.1 server administration API.
- This action cannot be undone.
Parameters
- idUUID
The ID of the OAuth client to delete.
try await admin.oauth.deleteClient( id: UUID(uuidString: "12345678-1234-1234-1234-123456789012")!)Regenerate client secret
Regenerate the secret for an OAuth client.
- Requires
secretkey. - This method is part of the OAuth 2.1 server administration API.
- The old secret will be immediately invalidated.
- Make sure to update your application with the new secret.
Parameters
- idUUID
The ID of the OAuth client whose secret should be regenerated.
let client = try await admin.oauth.regenerateClientSecret( id: UUID(uuidString: "12345678-1234-1234-1234-123456789012")!)// Store the new secret in your secret manager. Do not log it.if let secret = client.clientSecret { try await secretManager.store(secret, name: "oauth-client-secret")}print("Rotated the OAuth client secret")Invokes a Supabase Edge Function.
Invoke a Supabase Edge Function. invoke buffers the whole response. It returns a FunctionResponse with the status, headers, and body, or decodes the body into a Decodable type.
- The client sends the signed-in user's access token in the
Authorizationheader, or the API key when there is no session. AnAuthorizationheader that you pass inFunctionInvokeOptions.headerswins. - Pass the body as a
FunctionBody. Each factory sets theContent-Type:.json(_:)sendsapplication/json,.text(_:)sendstext/plain; charset=utf-8, and.data(_:contentType:)sendsapplication/octet-streamunless you pass another type. AContent-TypeinFunctionInvokeOptions.headersoverrides it. .json(_:)encodes andinvokedecodes with the SDK's coders, which write and readDateas ISO 8601. Passdecoder:toinvoke, orencoder:to.json(_:encoder:), to change that.- When a region is specified, both the
x-regionheader andforceFunctionRegionquery parameter are set to ensure proper function routing. - By default, function invocations use a 150-second idle timeout. You can override this per call with
FunctionInvokeOptions(timeout:). This only controls the client's request timeout — it cannot extend function execution beyond the platform's 150-second gateway idle timeout, after which a 504 Gateway Timeout is returned regardless of the value passed.
struct Response: Decodable { // Expected response definition}let response: Response = try await supabase.functions.invoke( "hello", body: .json(["foo": "bar"]))// Or name the type with `as:`let same = try await supabase.functions.invoke( "hello", body: .json(["foo": "bar"]), as: Response.self)Invoke a Supabase Edge Function and stream the response
Invoke a Supabase Edge Function and read the response body as it arrives. Use it for text/event-stream responses and large downloads.
streamreturns aFunctionStreamResponseas soon as the response head arrives. Itsbodyis anHTTPBody, anAsyncSequenceofArraySlice<UInt8>chunks. Iterate it once.- A relay failure or a non-2xx status throws a
FunctionsErrorfromstreamitself, before you read the body. - Chunk boundaries follow the network, not the payload. A server-sent event can arrive split across two chunks, so buffer the bytes and frame the events yourself.
- Cancelling the task that reads the body closes the connection and throws
CancellationErrorfrom the loop. streamtakes the samebodyandoptionsasinvoke.
let response = try await supabase.functions.stream( "hello", body: .json(["foo": "bar"]))// Write each chunk to a file, so memory use stays small.let fileURL = FileManager.default.temporaryDirectory .appendingPathComponent("hello-response")FileManager.default.createFile(atPath: fileURL.path, contents: nil)let file = try FileHandle(forWritingTo: fileURL)defer { try? file.close() }for try await chunk in response.body { try file.write(contentsOf: chunk)}Subscribe to channel
- By default, Broadcast and Presence are enabled for all projects.
- By default, listening to database changes is disabled for new projects due to database performance and security concerns. You can turn it on by managing Realtime's replication.
- You can receive the "previous" data for updates and deletes by setting the table's
REPLICA IDENTITYtoFULL(e.g.,ALTER TABLE your_table REPLICA IDENTITY FULL;). - Row level security is not applied to delete statements. When RLS is enabled and replica identity is set to full, only the primary key is sent to clients.
- Every listener is an
AsyncStream. Get the channel withawait supabase.channel(_:), open the streams, calltry await channel.subscribe(), then iterate. To stop listening, cancel the task that iterates the stream. - Open presence streams before calling
subscribe(): they turn presence on for the join. A presence stream opened after the join, while presence is off, reports an issue and ends at once. A Postgres changes stream opened after the join makes the channel leave and join again with the new binding. subscribe()has no attempt limit. It retries until the join succeeds, fails for good, or its task is cancelled. It throws aRealtimeErrorwhen a retry cannot help, for example when an RLS policy refuses the join.broadcastandtrackthrow aRealtimeErrorof kind.notSubscribedwhen the channel is not subscribed.
// This client sends the message too, so it must receive its own messages.let channel = await supabase.channel("room1") { $0.broadcast.receivesOwnMessages = true}let broadcastStream = await channel.broadcasts(event: "cursor-pos")try await channel.subscribe()Task { for await message in broadcastStream { print("Cursor position received", message.payload) }}try await channel.broadcast( event: "cursor-pos", payload: [ "x": Double.random(in: 0...1), "y": Double.random(in: 0...1) ])Unsubscribe from a channel
Unsubscribes and removes Realtime channel from Realtime client.
- Removing a channel is a great way to maintain the performance of your project's Realtime service as well as your database if you're listening to Postgres changes.
- Supabase will automatically handle cleanup 30 seconds after a client is disconnected, but unused channels may cause degradation as more clients are simultaneously subscribed.
removeChannel(_:)ends every stream opened on the channel. The channel is then spent: its actions throw aRealtimeErrorof kind.channelRemoved. Get a new channel fromsupabase.channel(_:).channel.unsubscribe()only leaves the topic. The channel and its streams stay, andsubscribe()joins again.- After you remove the last channel, the client disconnects from the Realtime websocket after
disconnectOnEmptyChannelsAfter(50 seconds by default). Set it to.zeroinSupabaseClient.Configuration.Realtimeto disconnect at once.
let channel = await supabase.channel("channelId")//...await supabase.removeChannel(channel)Unsubscribe from all channels
Unsubscribes and removes all Realtime channels from Realtime client.
- Removing channels is a great way to maintain the performance of your project's Realtime service as well as your database if you're listening to Postgres changes. Supabase will automatically handle cleanup 30 seconds after a client is disconnected, but unused channels may cause degradation as more clients are simultaneously subscribed.
removeAllChannels()ends every stream on every channel, then disconnects from the Realtime websocket at once. It ignoresdisconnectOnEmptyChannelsAfter.
await supabase.removeAllChannels()Retrieve all channels
Returns all Realtime channels that the client created and has not removed. The read is async, and the order is not specified.
let channels = await supabase.channelsFile Buckets
This section contains methods for working with File Buckets.
supabase.storage is a StorageClient. Call from(_:) to get a StorageBucket for file operations. Every failed request throws StorageError.
List all buckets
- RLS policy permissions required:
bucketstable permissions:selectobjectstable permissions: none
- Refer to the Storage guide on how access control works
let buckets = try await supabase.storage .listBuckets()Retrieve a bucket
- RLS policy permissions required:
bucketstable permissions:selectobjectstable permissions: none
- Refer to the Storage guide on how access control works
let bucket = try await supabase.storage .bucket("avatars")Create a bucket
- RLS policy permissions required:
bucketstable permissions:insertobjectstable permissions: none
- Refer to the Storage guide on how access control works
- Returns the name of the new bucket. You can ignore the result.
- A field you leave as
niltakes the server default: a private bucket with no size or MIME type limit.
try await supabase.storage .createBucket( "avatars", options: CreateBucketOptions( isPublic: false, fileSizeLimit: .megabytes(1), allowedMimeTypes: ["image/png"] ) )Empty a bucket
- RLS policy permissions required:
bucketstable permissions:selectobjectstable permissions:selectanddelete
- Refer to the Storage guide on how access control works
try await supabase.storage .emptyBucket("avatars")Update a bucket
- RLS policy permissions required:
bucketstable permissions:selectandupdateobjectstable permissions: none
- Refer to the Storage guide on how access control works
- Only the fields you set are sent. The other settings keep their current value. Storage rejects an update that sets no field.
try await supabase.storage .updateBucket( "avatars", options: UpdateBucketOptions( isPublic: false, fileSizeLimit: .megabytes(1), allowedMimeTypes: ["image/png"] ) )Delete a bucket
- RLS policy permissions required:
bucketstable permissions:selectanddeleteobjectstable permissions: none
- Refer to the Storage guide on how access control works
try await supabase.storage .deleteBucket("avatars")Upload a file
- RLS policy permissions required:
bucketstable permissions: noneobjectstable permissions: onlyinsertwhen you are uploading new files andselect,insertandupdatewhen you are upserting files
- Refer to the Storage guide on how access control works
- Pass
data:for bytes in memory orfileURL:for a file on disk. ThefileURL:overload streams the file and infers the content type from the file extension. - The request body is the raw file, not
multipart/form-data.metadatagoes in thex-metadataheader. - If you do not set
upsert, Storage does not replace an existing file.
let fileName = "avatar1.png"let object = try await supabase.storage .from("avatars") .upload( path: "public/\(fileName)", data: fileData, options: UploadOptions( contentType: "image/png", cacheControl: .maxAge(.seconds(3600)), upsert: false ) )Replace an existing file
- RLS policy permissions required:
bucketstable permissions: noneobjectstable permissions:updateandselect
- Refer to the Storage guide on how access control works
updatealways replaces the file and ignoresupsert. The file must already exist.
let fileName = "avatar1.png"try await supabase.storage .from("avatars") .update( path: "public/\(fileName)", data: fileData, options: UploadOptions( contentType: "image/png", cacheControl: .maxAge(.seconds(3600)) ) )Move an existing file
- RLS policy permissions required:
bucketstable permissions: noneobjectstable permissions:updateandselect
- Refer to the Storage guide on how access control works
- Pass
toBucket:to move the file into a different bucket.
try await supabase .storage .from("avatars") .move(from: "public/avatar1.png", to: "private/avatar2.png")Copy an existing file
- RLS policy permissions required:
bucketstable permissions: noneobjectstable permissions:insertandselect
- Refer to the Storage guide on how access control works
- Returns an
UploadedObject. ItsfullPathholds the key of the copy. PasstoBucket:to copy the file into a different bucket.
let copy = try await supabase .storage .from("avatars") .copy(from: "public/avatar1.png", to: "private/avatar2.png")print(copy.fullPath) // "avatars/private/avatar2.png"Create a signed URL
- RLS policy permissions required:
bucketstable permissions: noneobjectstable permissions:select
- Refer to the Storage guide on how access control works
expiresInis aDuration. Storage rejects a value less than one second.
let signedURL = try await supabase.storage .from("avatars") .createSignedURL(path: "folder/avatar1.png", expiresIn: .seconds(60))Create signed URLs
- RLS policy permissions required:
bucketstable permissions: noneobjectstable permissions:select
- Refer to the Storage guide on how access control works
- Returns one
SignedURLResultper path, in order. A path that does not exist gives a.failureresult and does not throw.
let results = try await supabase .storage .from("avatars") .createSignedURLs( paths: ["folder/avatar1.png", "folder/avatar2.png"], expiresIn: .seconds(60) )for result in results { switch result { case .success(let path, let signedURL): print(path, signedURL) case .failure(let path, let error): print(path, "failed:", error) }}Create signed upload URL
Create a signed upload URL that can be used to upload files to a bucket.
- RLS policy permissions required:
bucketstable permissions: noneobjectstable permissions:insert
- Refer to the Storage guide on how access control works
- Signed upload URLs are valid for 2 hours. Pass the returned
tokentouploadToSignedURL().
let signedUpload = try await supabase.storage .from("avatars") .createSignedUploadURL(path: "folder/avatar1.png")Upload to a signed URL
Upload a file to a bucket using a signed URL.
- Use this method to upload files using a signed upload URL created with
createSignedUploadURL(). - The token decides whether an existing file is replaced.
upsertinUploadOptionsis ignored.
let fileData = Data("Hello World".utf8)try await supabase.storage .from("avatars") .uploadToSignedURL( path: "folder/avatar1.png", token: "your-signed-token", data: fileData, options: UploadOptions( contentType: "text/plain" ) )Retrieve public URL
- The bucket needs to be set to public, either via updateBucket() or by going to Storage on supabase.com/dashboard, clicking the overflow menu on a bucket and choosing "Make public"
- RLS policy permissions required:
bucketstable permissions: noneobjectstable permissions: none
- Refer to the Storage guide on how access control works
publicURLdoes not throw and does not send a request.
let publicURL = supabase.storage .from("public-bucket") .publicURL(path: "folder/avatar1.png")Download a file
- RLS policy permissions required:
bucketstable permissions: noneobjectstable permissions:select
- Refer to the Storage guide on how access control works
- Returns a
DownloadResponseas soon as the response headers arrive. Read the body once, withdata()orwrite(to:).
let data = try await supabase.storage .from("avatars") .download(path: "folder/avatar1.png") .data()Delete files in a bucket
- RLS policy permissions required:
bucketstable permissions: noneobjectstable permissions:deleteandselect
- Refer to the Storage guide on how access control works
- Returns the removed files as
[StorageObject]. You can ignore the result.
try await supabase.storage .from("avatars") .remove(paths: ["folder/avatar1.png"])List all files in a bucket
- RLS policy permissions required:
bucketstable permissions: noneobjectstable permissions:select
- Refer to the Storage guide on how access control works
- Options you do not set are not sent. Storage then returns 100 entries from offset 0, sorted by name in ascending order.
let files = try await supabase.storage .from("avatars") .list( path: "folder", options: ListOptions( limit: 100, offset: 0, sortBy: .name, order: .ascending ) )