Skip to content

swift Client Library

supabase-swiftView on GitHub

This 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:

  • Auth
  • Functions
  • PostgREST
  • Realtime
  • Storage

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.2
let 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 place
grant 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 on
grant 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 a global group for all of them.
  • Debug builds log warnings and errors to stderr by default. Release builds stay silent.
import Supabase
let 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

  1. Install Xcode 26.0 or later. v3 needs Swift 6.2 or later, which Xcode 26.0 includes.
  2. Update the supabase-swift package requirement to 3.0.0-alpha.2.
  3. 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 Logging
import Supabase
var logger = Logger(label: "myapp")
logger.logLevel = .debug
let 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:

  • AnyJSON is renamed to JSONValue. Numbers are one case, .number(JSONNumber), which keeps every digit.
  • supabase.realtimeV2 is renamed to supabase.realtime, and supabase.channel(_:) is async.
  • supabase.handle(_:) is renamed to supabase.handleRedirect(_:).
  • Methods that only read a value drop their get prefix. For example, getPublicURL is publicURL.
  • Arguments that name an identifier are id:, and acronyms keep their capitals, as in factorID.

v3 removes the following:

  • supabase.database. Use supabase.from(_:), supabase.rpc(_:), and supabase.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 Modifiers
  • select() can be combined with Filters
  • If using the Supabase hosted platform apikey is 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 value property of the response. Declare a Decodable type and annotate the variable, so the client knows what to decode.
  • Failed queries throw a PostgrestError. Its code holds the PostgreSQL or PostgREST error code, such as PGRST116.
  • v3 also has an experimental typed query API: the @Table macro and from(Todo.self). It needs @_spi(Experimental) import Supabase and 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()
.value

Insert data

  • insert() returns no rows by default. Add select() to the chain to get the inserted rows back.
  • You can't add filters after insert(). Modifiers such as select() and single() still work.
  • If values fails to encode, insert() throws a PostgrestError of kind .invalidRequest and 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. Add select() 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 values to use upsert.
  • upsert() returns no rows by default. Add select() to the chain to get the rows back.
  • You can't add filters after upsert(). Modifiers such as select() and single() 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 through SELECT policies are deleted. Note that by default no rows are visible, so you need at least one SELECT/ALL policy that makes the rows visible.
  • delete() returns no rows by default. Add select() 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=strict and max-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()
.value

Using 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") // Correct
try 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.

  • config sets the text search configuration, such as "english".
  • type picks how query is parsed: .plain, .phrase, or .websearch. Leave it out to use to_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 values
try 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()
.value

Order the results

Order the query result by column.

  • nullsFirst defaults to nil, so the database picks where NULL values go: last on an ascending sort, first on a descending sort. Pass true or false to 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 PostgrestError with code PGRST116 and status 406, the same error that single() throws.
  • maybeSingle() requests the usual JSON array and counts the rows in the client. On a write, such as update(...).select().maybeSingle(), every matched row is written before the count is checked. Use single() 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()
.value

Retrieve 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 a PostgrestError of kind .invalidRequest before 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()
.value

Using 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 format parameter takes an ExplainFormat value: .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-end setting 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.

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.auth

Create 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.
  • The result also has user and session properties. session is nil when the user must confirm first.
  • When the user confirms their email address, they are redirected to the SITE_URL by default. You can modify your SITE_URL or 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 .confirmationRequired with an obfuscated/fake user object that has an empty identities list.
    • 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 signed-in user, use user().

Parameters

  • email
    Optional
    String

    One of email or phone must be provided.

  • phone
    Optional
    String

    One of email or phone must be provided.

  • passwordString
  • options
    Optional
    SignUpOptions

    The user metadata (userMetadata, a JSONObject), 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 AuthChange has event, session, status (an AuthStatus), and signOutReason.
  • Events are delivered asynchronously. To read the state right after a call, use supabase.auth.status or supabase.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 most initialRefreshTimeout (5 seconds by default). Check session.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.
      • signOutReason tells .userInitiated apart from .sessionExpired, .sessionRevoked, and .sessionMissing.
      • Use this to clean up any local storage your application has associated with the user.
    • 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:) or linkIdentity finishes successfully, after unlinkIdentity(_:) 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.
    • passwordRecovery
      • Emitted instead of the signedIn event when the user opens a password recovery link, or verifies a code with verifyOTP and type .recovery.
      • Use it to show a UI to the user where they can reset their password.
    • 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 captchaToken param.
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

  • email
    Optional
    String

    One of email or phone must be provided.

  • phone
    Optional
    String

    One of email or phone must be provided.

  • passwordString
  • captchaToken
    Optional
    String
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 Nonce for each attempt. Send nonce.hashed to the provider and pass nonce.raw to 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, set shouldCreateUser to false in 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 to handleRedirect(_:).
  • 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

  • email
    Optional
    String

    One of email or phone must be provided.

  • phone
    Optional
    String

    One of email or phone must be provided.

  • options
    Optional
    EmailOTPOptions | PhoneOTPOptions

    EmailOTPOptions for an email: shouldCreateUser, userMetadata, redirectTo (the redirect URL embedded in the email link), and captchaToken. PhoneOTPOptions for a phone: shouldCreateUser, userMetadata, channel (.sms or .whatsapp), and captchaToken. When shouldCreateUser or channel is nil, 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 redirectTo in 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.

  • options
    Optional
    OAuthOptions

    scopes (an array of scopes to request), redirectTo (a URL to send the user to after they are confirmed), and queryItems (additional query items).

  • presenter
    Optional
    WebAuthPresenter

    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 .domain to 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 an OAuthFlow with 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.

  • options
    Optional
    SSOOptions

    redirectTo, the URL to redirect the user to after they have signed in, which must be a configured redirect URL for your Supabase instance, and captchaToken.

  • presenter
    Optional
    WebAuthPresenter

    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.ethereum the signature is a 0x-prefixed hex encoded string. For Web3Chain.solana it 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 signedIn auth change event is emitted.
  • anchor is the window to show the sheet from. nil uses 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 Supabase
let session = try await supabase.auth.passkeys.signIn()
let user = session.user

Register 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 with passkeys.rename(id:friendlyName:).
  • anchor is the window to show the sheet from. nil uses 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 Supabase
let 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 as subject, email, role, sessionID, and expiresAt.
  • 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 kid header 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 a kid, 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 exp or sub claim fails verification. The anon key and the service role key have no sub, so claims(jwt:) rejects them.

Parameters

  • jwt
    Optional
    String

    The JWT to verify. Use claims(options:) to verify the access token from the current session.

  • options
    Optional
    ClaimsOptions

    Options for JWT verification. Can specify allowsExpired to skip expiration check and jwks to 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.
  • .local removes the session, clears pending PKCE flows, and emits .signedOut before the request, so the device is signed out whatever the server answers.
  • .global ends 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.
  • .others ends every other session of the user and keeps this one. It throws an error of kind .sessionMissing when no session is stored.
  • With no stored session, .local and .global still 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 with updateUser(_:redirectTo:).
  • The call succeeds for an unknown email too, so it does not show which addresses have an account.

Parameters

  • emailString
  • options
    Optional
    ResetPasswordOptions

    redirectTo, the URL that the reset link opens, and captchaToken.

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 verifyOTP method takes in different verification types. If a phone number is used, the type can either be .sms or .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 verifyOTP to sign up / sign-in a user.
  • verifyOTP(phone:token:type:) returns the Session. verifyOTP(email:token:type:) and verifyOTP(tokenHash:type:) return a VerifyOTPResult: .signedIn(session), or .emailChangePending(message:) for the first confirmation of a secure email change.
  • The event follows the type: .passwordRecovery for .recovery, .userUpdated for an email or phone change of the signed-in user, and .signedIn otherwise.
  • 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

  • email
    Optional
    String

    One of phone, email, or tokenHash must be provided.

  • phone
    Optional
    String

    One of phone, email, or tokenHash must be provided.

  • tokenHash
    Optional
    String

    The token hash from the user's email link. One of phone, email, or tokenHash must be provided.

  • typeEmailOTPType | PhoneOTPType
  • token
    Optional
    String

    The OTP sent to the user. Required if using phone or email.

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 AuthError of kind .sessionMissing when no session is stored, and of kind .sessionInvalidated when the server rejects the refresh of an expired session.
  • With autoRefresh: .disabled, it throws an error of kind .refreshDisabled when 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 .signedOut event 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, currentUser is 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 userMetadata as 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.id is the Supabase identity UUID (identity_id in JSON). The user's ID at the provider is providerUserID.
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 new Session.
  • To show the page yourself, use linkIdentityURL(_:options:). It returns an OAuthFlow with the URL to open.

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 currentUser keeps the old identities and no .userUpdated is emitted. Call user() to read the identities again. Do not retry the unlink.

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 .signedIn once. 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_INTERVAL which 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 .oauthFlowFailed without a request.
  • Pass the id of the OAuthFlow from oauthSignInURL, linkIdentityURL, or ssoSignInURL as flowID. 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 after stopAutoRefresh().
  • Under .manual and .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: .manual or .disabled in the client configuration. Use .disabled in 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 status is no longer .loading.
  • The client reads storage asynchronously after it is created. Until then, currentSession is nil. Call this method before you read currentSession or currentUser at 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:) and enrollPhone(_:friendlyName:). Each returns the data for that factor type.
  • The new factor is unverified. Use its id to 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.id
let qrCode = enrollment.qrCode
let secret = enrollment.secret
let uri = enrollment.uri

Create a challenge

  • An enrolled factor is required before creating a challenge.
  • For a phone factor, this call sends the code. Pass channel: .whatsapp to send it through WhatsApp. The server default is SMS.
  • To verify a challenge, see mfa.verify().
  • expiresAt is a Date.
let challenge = try await supabase.auth.mfa.challenge(
factorID: UUID(uuidString: "34e770dd-9ff9-416c-87fa-43b31d7ef225")!
)
let challengeID = challenge.id
let expiresAt = challenge.expiresAt

Verify a challenge

  • To verify a challenge, please create a challenge first.
  • On success, the client stores the upgraded aal2 session, signs out the user's other sessions, and emits .mfaChallengeVerified. Verifying an unverified factor also marks it verified.
  • 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() and mfa.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

let response = try await supabase.auth.mfa.unenroll(
factorID: UUID(uuidString: "34e770dd-9ff9-416c-87fa-43b31d7ef225")!
)
print(response.id) // ID of the unenrolled factor

Get Authenticator Assurance Level

  • Authenticator Assurance Level (AAL) is the measure of the strength of an authentication mechanism.
  • In Supabase, having an AAL of aal1 refers to having the 1st factor of authentication such as an email and password or OAuth sign-in while aal2 refers to the 2nd factor of authentication such as a time-based, one-time-password (TOTP).
  • If the user has a verified factor, the nextLevel field will return aal2, else, it will return the current level.
  • The method fetches the user from the server, so nextLevel includes factors enrolled on other devices.
  • With no session, it throws an AuthError of kind .sessionMissing.
let aal = try await supabase.auth.mfa.assuranceLevel()
let currentLevel = aal.currentLevel
let nextLevel = aal.nextLevel
let currentAuthenticationMethods = aal.currentAuthenticationMethods

List 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 verified and unverified. all returns both. Filter on factorType for one type.
  • verified includes the recovery codes factor, which cannot be challenged.
let factors = try await supabase.auth.mfa.factors()
let verified = factors.verified
let unverified = factors.unverified

GetRecoveryCodesStatusAsync()

  • Returns how many codes the current set holds and how many are unused. It never returns the codes.
  • Works at any assurance level. When remaining reaches zero, ask the user to regenerate the codes.
  • Throws an error with code mfa_factor_not_found when 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.codes

RegenerateRecoveryCodesAsync()

  • 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_found when the user has no recovery codes. Use generate(friendlyName:) instead.
let regenerated = try await supabase.auth.mfa.recoveryCodes.regenerate()
let codes = regenerated.codes

VerifyRecoveryCodeAsync()

  • 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 aal1 sessions, 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 factor

Auth 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 Supabase
let passkeys: [PasskeyListItem] = try await supabase.auth.passkeys.list()

Update a passkey

Updates the friendly name of a passkey. Limited to 120 characters.

Parameters

  • id
    Required
    UUID

    ID of the passkey to rename.

  • friendlyName
    Required
    String

    New human readable name. Limited to 120 characters.

// @_spi(Experimental) import Supabase
let 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

  • id
    Required
    UUID

    ID of the passkey to delete.

// @_spi(Experimental) import Supabase
try 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 (W3C PublicKeyCredentialCreationOptions) to the platform authenticator.
  • After running the authenticator, submit the result with passkeys.verifyRegistration(challengeID:credential:).
  • challengeID is a UUID and expiresAt is a Date.
// @_spi(Experimental) import Supabase
let 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

  • challengeID
    Required
    UUID

    The challengeID returned by passkeys.registrationOptions().

  • credential
    Required
    JSONValue

    The W3C PublicKeyCredential JSON produced by the authenticator.

// @_spi(Experimental) import Supabase
let 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 (W3C PublicKeyCredentialRequestOptions) to the platform authenticator.
  • After running the authenticator, submit the result with passkeys.verifyAuthentication(challengeID:credential:).
// @_spi(Experimental) import Supabase
let 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

  • challengeID
    Required
    UUID

    The challengeID returned by passkeys.authenticationOptions().

  • credential
    Required
    JSONValue

    The W3C PublicKeyCredential JSON produced by the authenticator.

// @_spi(Experimental) import Supabase
let session: Session = try await supabase.auth.passkeys.verifyAuthentication(
challengeID: options.challengeID,
credential: credential
)
let user = session.user

Auth Admin

  • Admin methods live on AuthAdminClient, a separate client. supabase.auth.admin does not exist in v3.
  • AuthAdminClient requires a secret key. 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 secret key in a browser or mobile app.
  • Unlike the other clients, the AuthAdminClient initializer does not throw.
import Supabase
let 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 one UserPage. Pages start at 1.
  • To walk every page, iterate users(pageSize:). It fetches each page as you go.
let page = try await admin.listUsers()
let users = page.users

Create a user

Create a new user.

  • The server sends no confirmation email. Set confirmsEmail or confirmsPhone to true to 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 the auth.users.id column.
  • Pass softDelete: true to disable the account and keep its data. With no softDelete, 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.

  • userMetadata is stored in the user's user_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")
)


Update a user

Update user by ID.

  • The server changes only the fields you set in AdminUpdateUser.
  • banDuration is a Duration. Pass .zero to 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 .global scope, which revokes every session for the user. Pass .local to revoke only the session tied to the given JWT, or .others to 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 secret key.
  • 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 secret key.
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 Supabase
let 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 Supabase
try 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 secret key.
  • Build the settings with CreateCustomProvider.oauth2(...) or CreateCustomProvider.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_failed error 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 secret key.
let provider = try await admin.customProviders.provider(identifier: "custom:acme")

AdminAuth().ListCustomProvidersAsync()

List the custom providers.

  • Requires secret key.
  • Pass type: to list only the providers of one type.
let providers = try await admin.customProviders.list()

AdminAuth().UpdateCustomProviderAsync()

Update a custom provider.

  • Requires secret key.
  • 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 secret key.
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 secret key.
  • 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 secret key.
  • 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.clientID
let clientSecret = client.clientSecret

Get OAuth client

Get details of a specific OAuth client.

  • Requires secret key.
  • 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 secret key.
  • This method is part of the OAuth 2.1 server administration API.
  • The server changes only the fields you set in UpdateOAuthClient. redirectURIs and grantTypes replace 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 secret key.
  • 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 secret key.
  • 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 Authorization header, or the API key when there is no session. An Authorization header that you pass in FunctionInvokeOptions.headers wins.
  • Pass the body as a FunctionBody. Each factory sets the Content-Type: .json(_:) sends application/json, .text(_:) sends text/plain; charset=utf-8, and .data(_:contentType:) sends application/octet-stream unless you pass another type. A Content-Type in FunctionInvokeOptions.headers overrides it.
  • .json(_:) encodes and invoke decodes with the SDK's coders, which write and read Date as ISO 8601. Pass decoder: to invoke, or encoder: to .json(_:encoder:), to change that.
  • When a region is specified, both the x-region header and forceFunctionRegion query 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.

  • stream returns a FunctionStreamResponse as soon as the response head arrives. Its body is an HTTPBody, an AsyncSequence of ArraySlice<UInt8> chunks. Iterate it once.
  • A relay failure or a non-2xx status throws a FunctionsError from stream itself, 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 CancellationError from the loop.
  • stream takes the same body and options as invoke.
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 IDENTITY to FULL (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 with await supabase.channel(_:), open the streams, call try 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 a RealtimeError when a retry cannot help, for example when an RLS policy refuses the join.
  • broadcast and track throw a RealtimeError of kind .notSubscribed when 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 a RealtimeError of kind .channelRemoved. Get a new channel from supabase.channel(_:).
  • channel.unsubscribe() only leaves the topic. The channel and its streams stay, and subscribe() joins again.
  • After you remove the last channel, the client disconnects from the Realtime websocket after disconnectOnEmptyChannelsAfter (50 seconds by default). Set it to .zero in SupabaseClient.Configuration.Realtime to 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 ignores disconnectOnEmptyChannelsAfter.
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.channels

File 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:
    • buckets table permissions: select
    • objects table 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:
    • buckets table permissions: select
    • objects table 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:
    • buckets table permissions: insert
    • objects table 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 nil takes 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:
    • buckets table permissions: select
    • objects table permissions: select and delete
  • Refer to the Storage guide on how access control works
try await supabase.storage
.emptyBucket("avatars")

Update a bucket

  • RLS policy permissions required:
    • buckets table permissions: select and update
    • objects table 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:
    • buckets table permissions: select and delete
    • objects table 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:
    • buckets table permissions: none
    • objects table permissions: only insert when you are uploading new files and select, insert and update when you are upserting files
  • Refer to the Storage guide on how access control works
  • Pass data: for bytes in memory or fileURL: for a file on disk. The fileURL: overload streams the file and infers the content type from the file extension.
  • The request body is the raw file, not multipart/form-data. metadata goes in the x-metadata header.
  • 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:
    • buckets table permissions: none
    • objects table permissions: update and select
  • Refer to the Storage guide on how access control works
  • update always replaces the file and ignores upsert. 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:
    • buckets table permissions: none
    • objects table permissions: update and select
  • 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:
    • buckets table permissions: none
    • objects table permissions: insert and select
  • Refer to the Storage guide on how access control works
  • Returns an UploadedObject. Its fullPath holds the key of the copy. Pass toBucket: 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:
    • buckets table permissions: none
    • objects table permissions: select
  • Refer to the Storage guide on how access control works
  • expiresIn is a Duration. 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:
    • buckets table permissions: none
    • objects table permissions: select
  • Refer to the Storage guide on how access control works
  • Returns one SignedURLResult per path, in order. A path that does not exist gives a .failure result 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:
    • buckets table permissions: none
    • objects table permissions: insert
  • Refer to the Storage guide on how access control works
  • Signed upload URLs are valid for 2 hours. Pass the returned token to uploadToSignedURL().
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. upsert in UploadOptions is 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:
    • buckets table permissions: none
    • objects table permissions: none
  • Refer to the Storage guide on how access control works
  • publicURL does 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:
    • buckets table permissions: none
    • objects table permissions: select
  • Refer to the Storage guide on how access control works
  • Returns a DownloadResponse as soon as the response headers arrive. Read the body once, with data() or write(to:).
let data = try await supabase.storage
.from("avatars")
.download(path: "folder/avatar1.png")
.data()

Delete files in a bucket

  • RLS policy permissions required:
    • buckets table permissions: none
    • objects table permissions: delete and select
  • 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:
    • buckets table permissions: none
    • objects table 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
)
)

Release Notes