mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 07:29:16 +00:00
## Problem supabase-swift v3 is in alpha (`3.0.0-alpha.2`). The docs have no reference for it. v3 renames many public APIs, so the v2 reference does not help people who try the alpha. ## Solution Add a v3 reference at `/reference/swift/v3`. v2 stays the default at `/reference/swift`. - **Prerelease flag.** A version in `REFERENCES` can now set `prerelease: 'alpha'` (or another stage). Swift versions are `['v2', 'v3', 'v1']`. `versions[0]` is still the latest stable version, so the existing URL and "latest" logic does not change. Other SDKs can use the same flag. - **Alpha notice.** A prerelease page shows "This version is in alpha" with a link to the stable version. It does not show the "Version out of date" warning. - **Version menu.** Prerelease versions show in a separate "Prereleases" group with a stage badge. - **Spec.** `spec/supabase_swift_v3.yml` ports the v2 spec to the v3 API. The examples were checked against the v3 source at the `v3.0.0-alpha.2` tag. It adds the new v3 APIs: MFA recovery codes, `AuthAdminClient`, admin custom providers, `functions.stream`, and the Realtime streams API. - **Pages.** New introduction, installing (Xcode 26, Swift 6.2), and upgrade guide pages under `docs/ref/swift/v3/`. - **Navigation.** Nav entries for v3. v3 is excluded from the "TypeScript support" section. Not in this PR: - Search indexing for v3. Search still covers v2 only. - In the v2 spec, 7 filter ids use camelCase (for example `containedBy` and `textSearch`). They match no section, so they do not render in the v2 docs today. The v3 spec uses the matching kebab-case ids. The v2 fix can be a separate PR. ## Review instructions 1. Open `/docs/reference/swift/v3` on the preview. See the alpha notice and the v3 sections. 2. Open the version menu. See "Stable releases" (v2.0 with a "Latest" badge, v1.0) and "Prereleases" (v3.0 with an "Alpha" badge). 3. Open `/docs/reference/swift`. See that it still shows v2 with no notice. 4. Read the upgrade guide at `/docs/reference/swift/v3/upgrade-guide`. Typecheck, Prettier, and ESLint pass locally. I did not run the docs unit tests. The Swift examples were not compiled. <img width="318" height="236" alt="Screenshot 2026-11-25 at 10 36 01" src="https://github.com/user-attachments/assets/0f0caf18-7a4a-4835-8f6a-b76df9c66fa9" /> <img width="685" height="417" alt="Screenshot 2026-11-25 at 10 36 10" src="https://github.com/user-attachments/assets/1c55bc44-1fc1-4390-8d8c-48bc55822bd3" /> ## Checklist Check all before review: - [ ] I have read [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) - [ ] If I wrote a new docs topic or edited an existing topic, I used the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs [style guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide)
6599 lines
236 KiB
YAML
6599 lines
236 KiB
YAML
openref: 0.1
|
|
|
|
info:
|
|
id: reference/supabase-swift
|
|
title: Supabase Swift Client
|
|
description: |
|
|
|
|
Supabase Swift v3 (alpha).
|
|
|
|
specUrl: https://github.com/supabase/supabase/edit/master/apps/docs/spec/supabase_swift_v3.yml
|
|
slugPrefix: '/'
|
|
libraries:
|
|
- id: 'Swift'
|
|
version: '3.0.0-alpha.2'
|
|
|
|
functions:
|
|
- id: initializing
|
|
title: 'Initializing'
|
|
description: |
|
|
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.
|
|
notes: |
|
|
- 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.
|
|
examples:
|
|
- id: initialize-client
|
|
name: Initialize Client
|
|
code: |
|
|
```swift
|
|
import Supabase
|
|
|
|
let supabase = try SupabaseClient(
|
|
supabaseURL: URL(string: "https://xyzcompany.supabase.co")!,
|
|
supabaseKey: "your-publishable-key"
|
|
)
|
|
```
|
|
- id: initialize-client-custom-options
|
|
name: Initialize Client with custom options
|
|
code: |
|
|
```swift
|
|
import Supabase
|
|
|
|
let supabase = try SupabaseClient(
|
|
supabaseURL: URL(string: "https://xyzcompany.supabase.co")!,
|
|
supabaseKey: "your-publishable-key",
|
|
configuration: SupabaseClient.Configuration(
|
|
database: .init(
|
|
schema: "public"
|
|
),
|
|
auth: .init(
|
|
storage: MyCustomAuthStorage() // conforms to AuthStorage
|
|
),
|
|
global: .init(
|
|
headers: [HTTPField.Name("x-my-custom-header")!: "my-app-name"],
|
|
http: .init(transport: URLSessionTransport(session: URLSession.myCustomSession))
|
|
)
|
|
)
|
|
)
|
|
```
|
|
description: |
|
|
Every field of `SupabaseClient.Configuration` is a `var`, so you can also build the value step by step:
|
|
|
|
```swift
|
|
var configuration = SupabaseClient.Configuration()
|
|
configuration.database.schema = "public"
|
|
configuration.global.headers[HTTPField.Name("x-my-custom-header")!] = "my-app-name"
|
|
|
|
let supabase = try SupabaseClient(
|
|
supabaseURL: URL(string: "https://xyzcompany.supabase.co")!,
|
|
supabaseKey: "your-publishable-key",
|
|
configuration: configuration
|
|
)
|
|
```
|
|
- id: initialize-client-with-retries
|
|
name: Initialize Client with automatic retries
|
|
description: |
|
|
PostgREST `GET` and `HEAD` requests automatically retry on a transient network failure, a 503, or a 520, up to three times, with jittered backoff. The client honors a `Retry-After` header. Retries are enabled by default and can be disabled per client.
|
|
code: |
|
|
```swift
|
|
import Supabase
|
|
|
|
let supabase = try SupabaseClient(
|
|
supabaseURL: URL(string: "https://xyzcompany.supabase.co")!,
|
|
supabaseKey: "your-publishable-key",
|
|
configuration: SupabaseClient.Configuration(
|
|
database: .init(
|
|
// Disable automatic retries for this client
|
|
retryEnabled: false
|
|
)
|
|
)
|
|
)
|
|
```
|
|
- id: initialize-client-with-logging
|
|
name: Initialize Client with Logging
|
|
description: |
|
|
The client logs through [swift-log](https://github.com/apple/swift-log). Add the `swift-log` package to your project and `import Logging` where you build the logger. One logger covers every module. Each entry carries a `system` metadata key (`auth`, `postgrest`, `storage`, `functions`, or `realtime`) that a `LogHandler` can filter on.
|
|
|
|
To silence the debug-build default, pass `Logger(label: "com.example.app") { _ in SwiftLogNoOpLogHandler() }`.
|
|
code: |
|
|
```swift
|
|
import Logging
|
|
import Supabase
|
|
|
|
var logger = Logger(label: "com.example.app")
|
|
logger.logLevel = .debug
|
|
|
|
let supabase = try SupabaseClient(
|
|
supabaseURL: URL(string: "https://xyzcompany.supabase.co")!,
|
|
supabaseKey: "your-publishable-key",
|
|
configuration: SupabaseClient.Configuration(
|
|
global: .init(
|
|
logger: logger
|
|
)
|
|
)
|
|
)
|
|
```
|
|
- id: initialize-client-with-custom-transport
|
|
name: Initialize Client with a custom transport and middleware
|
|
description: |
|
|
Every module sends requests through one `ClientTransport`, behind an ordered list of `ClientMiddleware`. Set both in `global.http`. `URLSessionTransport(session:)` wraps your own `URLSession`. Middlewares run in array order on the way out and in reverse order on the way back. In a module that retries (Auth, PostgREST, Storage), they run once per attempt.
|
|
|
|
The SDK sets the request timeout itself: 60 seconds, or 150 seconds for Edge Functions. `URLSessionConfiguration.timeoutIntervalForRequest` has no effect. Set `HTTPClientConfiguration(timeout:)` instead.
|
|
code: |
|
|
```swift
|
|
import Supabase
|
|
|
|
struct AppVersionMiddleware: ClientMiddleware {
|
|
func intercept(
|
|
_ request: HTTPRequest,
|
|
body: HTTPBody?,
|
|
next: nonisolated(nonsending) @Sendable (HTTPRequest, HTTPBody?) async throws
|
|
-> (HTTPResponse, HTTPBody?)
|
|
) async throws -> (HTTPResponse, HTTPBody?) {
|
|
var request = request
|
|
request.headerFields[HTTPField.Name("X-App-Version")!] = "2.1.0"
|
|
return try await next(request, body)
|
|
}
|
|
}
|
|
|
|
let supabase = try SupabaseClient(
|
|
supabaseURL: URL(string: "https://xyzcompany.supabase.co")!,
|
|
supabaseKey: "your-publishable-key",
|
|
configuration: SupabaseClient.Configuration(
|
|
global: .init(
|
|
http: .init(
|
|
transport: URLSessionTransport(session: URLSession.myCustomSession),
|
|
middlewares: [AppVersionMiddleware()],
|
|
timeout: .seconds(30)
|
|
)
|
|
)
|
|
)
|
|
)
|
|
```
|
|
- id: api-schemas
|
|
name: With custom schemas
|
|
code: |
|
|
```swift
|
|
import Supabase
|
|
|
|
let supabase = try SupabaseClient(
|
|
supabaseURL: URL(string: "https://xyzcompany.supabase.co")!,
|
|
supabaseKey: "your-publishable-key",
|
|
configuration: SupabaseClient.Configuration(
|
|
database: .init(
|
|
// Provide a custom schema. Defaults to "public".
|
|
schema: "other_schema"
|
|
)
|
|
)
|
|
)
|
|
```
|
|
description: |
|
|
By default the API server points to the `public` schema. You can enable other database schemas within the Dashboard.
|
|
Go to [Settings > API > Exposed schemas](/dashboard/project/_/settings/api) and add the schema which you want to expose to the API.
|
|
|
|
Note: `database.schema` sets the default schema for the client. Use `supabase.schema(_:)` to query another exposed schema for one request.
|
|
- id: initialize-client-with-opentelemetry
|
|
name: Initialize Client with OpenTelemetry tracing
|
|
description: |
|
|
Supabase Swift supports W3C `traceparent` header propagation via an opt-in SwiftPM package trait.
|
|
When enabled, the active OpenTelemetry span's trace context is automatically injected into every outgoing request across PostgREST, Storage, Auth, Functions, and Realtime — no additional runtime configuration needed.
|
|
|
|
Enable the `OpenTelemetry` trait in your `Package.swift` dependency declaration:
|
|
code: |
|
|
```swift
|
|
// Package.swift
|
|
.package(
|
|
url: "https://github.com/supabase/supabase-swift.git",
|
|
from: "3.0.0-alpha.2",
|
|
traits: ["OpenTelemetry"]
|
|
)
|
|
```
|
|
notes: |
|
|
- The trait is **off by default** — no OTel dependency is linked unless you opt in.
|
|
- When no span is active, the header is not added; it is always safe to call unconditionally.
|
|
- id: auth-api
|
|
title: 'Overview'
|
|
notes: |
|
|
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
|
|
|
|
```swift
|
|
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`:
|
|
|
|
```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:
|
|
|
|
```swift
|
|
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)`.
|
|
|
|
examples:
|
|
- id: create-auth-client
|
|
name: Create auth client
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
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
|
|
```
|
|
- id: create-auth-client-with-custom-storage
|
|
name: Create auth client with custom storage
|
|
isSpotlight: true
|
|
description: |
|
|
A custom storage conforms to `AuthStorage`, whose `load(key:)`, `save(_:key:)`, and `remove(key:)` methods are `async`. `load(key:)` returns `nil` when no value is stored. When you omit `storage`, the client uses the Keychain on Apple platforms and memory on other platforms.
|
|
code: |
|
|
```swift
|
|
// An in-memory store. Replace the dictionary with your own storage.
|
|
actor MyCustomStorage: AuthStorage {
|
|
private var values: [String: Data] = [:]
|
|
|
|
func load(key: String) async throws -> Data? { values[key] }
|
|
func save(_ data: Data, key: String) async throws { values[key] = data }
|
|
func remove(key: String) async throws { values[key] = nil }
|
|
}
|
|
|
|
let supabase = try SupabaseClient(
|
|
supabaseURL: URL(string: "https://xyzcompany.supabase.co")!,
|
|
supabaseKey: "your-publishable-key",
|
|
configuration: .init(
|
|
auth: .init(storage: MyCustomStorage())
|
|
)
|
|
)
|
|
let auth = supabase.auth
|
|
```
|
|
- id: sign-up
|
|
title: 'signUp()'
|
|
notes: |
|
|
- By default, the user needs to verify their email address before logging in. To turn this off, disable **Confirm email** in [your project](/dashboard/project/_/auth/providers).
|
|
- **Confirm email** determines if users need to confirm their email address after signing up.
|
|
- If **Confirm email** is enabled, 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`](/docs/guides/auth/redirect-urls) by default. You can modify your `SITE_URL` or add additional redirect URLs in [your project](/dashboard/project/_/auth/url-configuration).
|
|
- If `signUp()` is called for an existing confirmed user:
|
|
- When both **Confirm email** and **Confirm phone** (even when phone provider is disabled) are enabled in [your project](/dashboard/project/_/auth/providers), 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()`.
|
|
overwriteParams:
|
|
- name: email
|
|
isOptional: true
|
|
type: String
|
|
description: One of `email` or `phone` must be provided.
|
|
- name: phone
|
|
isOptional: true
|
|
type: String
|
|
description: One of `email` or `phone` must be provided.
|
|
- name: password
|
|
type: String
|
|
- name: options
|
|
isOptional: true
|
|
type: SignUpOptions
|
|
description: >
|
|
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`).
|
|
examples:
|
|
- id: sign-up
|
|
name: Sign up with email and password
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
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 ?? "")")
|
|
}
|
|
```
|
|
- id: sign-up-phone
|
|
name: Sign up with a phone number and password (SMS)
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let result = try await supabase.auth.signUp(
|
|
phone: "123456789",
|
|
password: "example-password",
|
|
options: SignUpOptions(channel: .sms)
|
|
)
|
|
```
|
|
- id: sign-up-phone-whatsapp
|
|
name: Sign up with a phone number and password (whatsapp)
|
|
isSpotlight: true
|
|
description: |
|
|
The user will be sent a WhatsApp message which contains a OTP. By default, a given user can only request a OTP once every 60 seconds. Note that a user will need to have a valid WhatsApp account that is linked to Twilio in order to use this feature.
|
|
code: |
|
|
```swift
|
|
let result = try await supabase.auth.signUp(
|
|
phone: "123456789",
|
|
password: "example-password",
|
|
options: SignUpOptions(channel: .whatsapp)
|
|
)
|
|
```
|
|
- id: sign-up-with-additional-user-metadata
|
|
name: Sign up with additional user metadata
|
|
isSpotlight: false
|
|
description: |
|
|
The metadata is a `JSONObject`, which is `[String: JSONValue]`. The SDK sends its keys as you wrote them. It does not convert them to snake_case.
|
|
code: |
|
|
```swift
|
|
let result = try await supabase.auth.signUp(
|
|
email: "example@email.com",
|
|
password: "example-password",
|
|
options: SignUpOptions(
|
|
userMetadata: [
|
|
"first_name": .string("John"),
|
|
"age": .number(24)
|
|
]
|
|
)
|
|
)
|
|
```
|
|
- id: sign-up-with-redirect
|
|
name: Sign up with a redirect URL
|
|
description: |
|
|
- You can provide a default redirect URL when initializing the client.
|
|
- See [redirect URLs and wildcards](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls) to add additional redirect URLs to your project.
|
|
- Pass the URL that opens your app to `handleRedirect(_:)` to finish the sign-up.
|
|
code: |
|
|
```swift
|
|
let result = try await supabase.auth.signUp(
|
|
email: "example@email.com",
|
|
password: "example-password",
|
|
options: SignUpOptions(
|
|
redirectTo: URL(string: "https://example.com/welcome")!
|
|
)
|
|
)
|
|
```
|
|
- id: on-auth-state-change
|
|
title: 'events()'
|
|
notes: |
|
|
- 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/guides/auth/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](/docs/guides/auth/passwords#resetting-a-users-password-forgot-password).
|
|
- `mfaChallengeVerified`
|
|
- Emitted when the user verifies an MFA challenge.
|
|
examples:
|
|
- id: listen-to-auth-changes
|
|
name: Listen to auth changes
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
for await change in supabase.auth.events() {
|
|
print(change.event, change.session?.user.id as Any)
|
|
}
|
|
```
|
|
description: |
|
|
- The loop runs until its task is canceled. To stop listening, cancel the task that runs the loop.
|
|
- id: list-to-a-specific-event
|
|
name: Listen to a specific event
|
|
code: |
|
|
```swift
|
|
for await change in supabase.auth.events() where change.event == .signedIn {
|
|
// handle signIn event.
|
|
}
|
|
```
|
|
- id: listen-to-auth-changes-in-a-task
|
|
name: Listen in a task and stop listening
|
|
code: |
|
|
```swift
|
|
let task = Task {
|
|
for await change in supabase.auth.events() {
|
|
if change.event == .signedOut {
|
|
showSignIn()
|
|
}
|
|
}
|
|
}
|
|
|
|
// Later, stop listening.
|
|
task.cancel()
|
|
```
|
|
- id: auth-js-gotrueclient-initialize
|
|
title: 'initialization()'
|
|
notes: |
|
|
- 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.
|
|
examples:
|
|
- id: wait-for-initial-session
|
|
name: Wait for the initial session
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
await supabase.auth.initialization()
|
|
|
|
if let session = supabase.auth.currentSession {
|
|
print("Signed in as \(session.user.id)")
|
|
}
|
|
```
|
|
- id: sign-in-anonymously
|
|
title: 'signInAnonymously()'
|
|
notes: |
|
|
- 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.
|
|
examples:
|
|
- id: sign-in-anonymously
|
|
name: Create an anonymous user
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let session = try await supabase.auth.signInAnonymously(captchaToken: captchaToken)
|
|
```
|
|
- id: sign-in-anonymously-with-user-metadata
|
|
name: Create an anonymous user with custom user metadata
|
|
isSpotlight: false
|
|
code: |
|
|
```swift
|
|
let session = try await supabase.auth.signInAnonymously(
|
|
userMetadata: ["theme": "dark"],
|
|
captchaToken: captchaToken
|
|
)
|
|
```
|
|
- id: sign-in-with-password
|
|
title: 'signIn()'
|
|
notes: |
|
|
- Requires either an email and password or a phone number and password.
|
|
- Returns the new session, stores it, and emits `.signedIn`.
|
|
overwriteParams:
|
|
- name: email
|
|
isOptional: true
|
|
type: String
|
|
description: One of `email` or `phone` must be provided.
|
|
- name: phone
|
|
isOptional: true
|
|
type: String
|
|
description: One of `email` or `phone` must be provided.
|
|
- name: password
|
|
type: String
|
|
- name: captchaToken
|
|
isOptional: true
|
|
type: String
|
|
examples:
|
|
- id: sign-in-with-email-and-password
|
|
name: Sign in with email and password
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
try await supabase.auth.signIn(
|
|
email: "example@email.com",
|
|
password: "example-password"
|
|
)
|
|
```
|
|
- id: sign-in-with-phone-and-password
|
|
name: Sign in with phone and password
|
|
isSpotlight: false
|
|
code: |
|
|
```swift
|
|
try await supabase.auth.signIn(
|
|
phone: "+13334445555",
|
|
password: "same-password"
|
|
)
|
|
```
|
|
- id: sign-in-with-otp
|
|
title: 'signInWithOTP()'
|
|
overwriteParams:
|
|
- name: email
|
|
isOptional: true
|
|
type: String
|
|
description: One of `email` or `phone` must be provided.
|
|
- name: phone
|
|
isOptional: true
|
|
type: String
|
|
description: One of `email` or `phone` must be provided.
|
|
- name: options
|
|
isOptional: true
|
|
type: EmailOTPOptions | PhoneOTPOptions
|
|
description: >
|
|
`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.
|
|
notes: |
|
|
- 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`](/docs/guides/auth/redirect-urls).
|
|
- See [redirect URLs and wildcards](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls) 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](/dashboard/project/_/auth/templates) to include `{{ .Token }}` instead of `{{ .ConfirmationURL }}`.
|
|
- See our [Twilio Phone Auth Guide](/docs/guides/auth/phone-login?showSmsProvider=Twilio) for details about configuring WhatsApp sign in.
|
|
examples:
|
|
- id: sign-in-with-email
|
|
name: Sign in with email
|
|
isSpotlight: true
|
|
description: The user will be sent an email which contains either a magiclink or a OTP or both. By default, a given user can only request a OTP once every 60 seconds.
|
|
code: |
|
|
```swift
|
|
try await supabase.auth.signInWithOTP(
|
|
email: "example@email.com",
|
|
options: EmailOTPOptions(
|
|
redirectTo: URL(string: "my-app-scheme://callback")!
|
|
)
|
|
)
|
|
```
|
|
- id: sign-in-with-sms-otp
|
|
name: Sign in with SMS OTP
|
|
isSpotlight: false
|
|
description: The user will be sent a SMS which contains a OTP. By default, a given user can only request a OTP once every 60 seconds.
|
|
code: |
|
|
```swift
|
|
try await supabase.auth.signInWithOTP(phone: "+13334445555")
|
|
```
|
|
- id: sign-in-with-whatsapp-otp
|
|
name: Sign in with WhatsApp OTP
|
|
isSpotlight: false
|
|
description: The user will be sent a WhatsApp message which contains a OTP. By default, a given user can only request a OTP once every 60 seconds. Note that a user will need to have a valid WhatsApp account that is linked to Twilio in order to use this feature.
|
|
code: |
|
|
```swift
|
|
try await supabase.auth.signInWithOTP(
|
|
phone: "+13334445555",
|
|
options: PhoneOTPOptions(channel: .whatsapp)
|
|
)
|
|
```
|
|
- id: sign-in-with-oauth
|
|
title: 'signInWithOAuth()'
|
|
overwriteParams:
|
|
- name: provider
|
|
type: Provider
|
|
description: >
|
|
The third-party provider. The first argument, without a label.
|
|
- name: options
|
|
type: OAuthOptions
|
|
isOptional: true
|
|
description: >
|
|
`scopes` (an array of scopes to request), `redirectTo` (a URL to send the user to after
|
|
they are confirmed), and `queryItems` (additional query items).
|
|
- name: presenter
|
|
type: WebAuthPresenter
|
|
isOptional: true
|
|
description: >
|
|
Shows the provider page and returns the callback URL. The default on Apple platforms is
|
|
`ASWebAuthenticationSessionPresenter`. On other platforms you must pass one.
|
|
notes: |
|
|
- This method is used for signing in using a third-party provider.
|
|
- Supabase supports many different [third-party providers](https://supabase.com/docs/guides/auth#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`.
|
|
examples:
|
|
- id: sign-in-using-ASWebAuthenticationSession
|
|
name: Sign in with OAuth using ASWebAuthenticationSession
|
|
isSpotlight: true
|
|
description: |
|
|
- The default presenter is `ASWebAuthenticationSessionPresenter`. Pass your own instance to set `prefersEphemeralWebBrowserSession`.
|
|
code: |
|
|
```swift
|
|
let session = try await supabase.auth.signInWithOAuth(
|
|
.github,
|
|
options: OAuthOptions(redirectTo: URL(string: "my-app-scheme://callback")!),
|
|
presenter: ASWebAuthenticationSessionPresenter(prefersEphemeralWebBrowserSession: true)
|
|
)
|
|
```
|
|
|
|
- id: sign-in-using-generic-flow
|
|
name: Sign in with OAuth and customize flow
|
|
isSpotlight: true
|
|
description: |
|
|
- Use a `ClosurePresenter` to open the page another way. The closure gets the URL and the callback scheme, and returns the callback URL.
|
|
code: |
|
|
```swift
|
|
let session = try await supabase.auth.signInWithOAuth(
|
|
.github,
|
|
presenter: ClosurePresenter { url, callbackScheme in
|
|
// use url to start OAuth flow
|
|
// and return the callback URL that contains the auth code.
|
|
// ...
|
|
return resultURL
|
|
}
|
|
)
|
|
```
|
|
|
|
- id: sign-in-using-manual-implementation
|
|
name: Sign in using a third-party provider
|
|
isSpotlight: true
|
|
description: |
|
|
- `oauthSignInURL()` starts a flow and returns an `OAuthFlow` with the `url` to open and the flow `id`.
|
|
- The `redirectTo` URL needs to be setup correctly in your project under Authentication -> URL Configuration -> Redirect URLs.
|
|
- Pass the callback URL to `handleRedirect(_:)`, or pass the code and `flow.id` to `exchangeCodeForSession(_:flowID:)`.
|
|
code: |
|
|
```swift
|
|
let flow = try await supabase.auth.oauthSignInURL(
|
|
.github,
|
|
options: OAuthOptions(redirectTo: URL(string: "my-app-scheme://callback")!)
|
|
)
|
|
|
|
// Open flow.url with your preferred method.
|
|
// When the app opens with the callback URL:
|
|
try await supabase.auth.handleRedirect(callbackURL)
|
|
```
|
|
|
|
- id: sign-in-with-scopes
|
|
name: Sign in with scopes
|
|
isSpotlight: false
|
|
description: |
|
|
If you need additional data from an OAuth provider, you can include a list of scopes in your request to get back an OAuth provider token.
|
|
You may also need to specify the scopes in the provider's OAuth app settings, depending on the provider. The list of scopes will be documented by the third-party provider you are using and specifying scopes will enable you to use the OAuth provider token to call additional APIs supported by the third-party provider to get more information.
|
|
code: |
|
|
```swift
|
|
let session = try await supabase.auth.signInWithOAuth(
|
|
.github,
|
|
options: OAuthOptions(scopes: ["repo", "gist", "notifications"])
|
|
)
|
|
```
|
|
- id: sign-in-with-id-token
|
|
title: 'signInWithIDToken()'
|
|
notes: |
|
|
- 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.
|
|
examples:
|
|
- id: sign-in-with-id-token
|
|
name: 'Sign In using ID Token'
|
|
description: Use this method to implement native Sign In With Apple.
|
|
code: |
|
|
```swift
|
|
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
|
|
)
|
|
)
|
|
```
|
|
- id: sign-in-with-sso
|
|
title: 'signInWithSSO()'
|
|
overwriteParams:
|
|
- name: target
|
|
type: SSOTarget
|
|
description: >
|
|
`.domain(String)`, the domain name of the organization to use SSO with, or
|
|
`.providerID(UUID)`, the UUID of the SSO provider.
|
|
- name: options
|
|
isOptional: true
|
|
type: SSOOptions
|
|
description: >
|
|
`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`.
|
|
- name: presenter
|
|
isOptional: true
|
|
type: WebAuthPresenter
|
|
description: >
|
|
Shows the identity provider page. The default on Apple platforms is
|
|
`ASWebAuthenticationSessionPresenter`. On other platforms you must pass one.
|
|
notes: |
|
|
- Before you can call this method you need to [establish a connection](/docs/guides/auth/enterprise-sso/auth-sso-saml#managing-saml-20-connections) to an identity provider. Use the [CLI commands](/docs/reference/cli/supabase-sso) 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.
|
|
examples:
|
|
- id: sign-in-with-domain
|
|
name: Sign in with email domain
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
// 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")!)
|
|
)
|
|
```
|
|
- id: sign-in-with-provider-uuid
|
|
name: Sign in with provider UUID
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
// Useful when you need to map a user's sign in request according
|
|
// to different rules that can't use email domains.
|
|
|
|
let session = try await supabase.auth.signInWithSSO(
|
|
.providerID(UUID(uuidString: "21648a9d-8d5a-4555-a9d1-d6375dc14e92")!)
|
|
)
|
|
```
|
|
- id: sign-in-with-web3
|
|
title: 'signInWithWeb3()'
|
|
description: |
|
|
Signs in a user via a signed Sign in with Ethereum (EIP-4361) or Sign in with Solana message.
|
|
notes: |
|
|
- Supports Ethereum (Sign-In with Ethereum) and Solana (Sign-In with Solana), both of which derive from the [EIP-4361](https://eips.ethereum.org/EIPS/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:)`.
|
|
examples:
|
|
- id: sign-in-with-ethereum
|
|
name: Sign in with an Ethereum wallet
|
|
isSpotlight: true
|
|
description: |
|
|
Sign the EIP-4361 message with the user's Ethereum wallet, then pass the message and its hex encoded signature.
|
|
code: |
|
|
```swift
|
|
let session = try await supabase.auth.signInWithWeb3(
|
|
Web3Credentials(
|
|
chain: .ethereum,
|
|
message: siweMessage,
|
|
signature: signatureHex
|
|
)
|
|
)
|
|
```
|
|
- id: sign-in-with-solana
|
|
name: Sign in with a Solana wallet
|
|
description: |
|
|
Sign the message with the user's Solana wallet, then pass the message and its base64 encoded signature.
|
|
code: |
|
|
```swift
|
|
let session = try await supabase.auth.signInWithWeb3(
|
|
Web3Credentials(
|
|
chain: .solana,
|
|
message: siwsMessage,
|
|
signature: signatureBase64
|
|
)
|
|
)
|
|
```
|
|
- id: sign-in-with-passkey
|
|
title: 'passkeys.signIn()'
|
|
notes: |
|
|
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.
|
|
examples:
|
|
- id: sign-in-with-passkey
|
|
name: Sign in with a passkey
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
// Must opt in: @_spi(Experimental) import Supabase
|
|
let session = try await supabase.auth.passkeys.signIn()
|
|
let user = session.user
|
|
```
|
|
- id: register-passkey
|
|
title: 'passkeys.register()'
|
|
notes: |
|
|
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`.
|
|
examples:
|
|
- id: register-passkey
|
|
name: Register a passkey for the current user
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
// Must opt in: @_spi(Experimental) import Supabase
|
|
let passkey = try await supabase.auth.passkeys.register()
|
|
print("Registered passkey \(passkey.id)")
|
|
```
|
|
- id: sign-out
|
|
title: 'signOut()'
|
|
notes: |
|
|
- 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`.
|
|
examples:
|
|
- id: sign-out
|
|
name: Sign out (this device)
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
try await supabase.auth.signOut()
|
|
```
|
|
- id: sign-out-all-sessions
|
|
name: Sign out (all sessions)
|
|
code: |
|
|
```swift
|
|
try await supabase.auth.signOut(scope: .global)
|
|
```
|
|
- id: sign-out-other-sessions
|
|
name: Sign out (other sessions)
|
|
code: |
|
|
```swift
|
|
try await supabase.auth.signOut(scope: .others)
|
|
```
|
|
- id: reset-password-for-email
|
|
title: 'resetPassword()'
|
|
notes: |
|
|
- 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.
|
|
overwriteParams:
|
|
- name: email
|
|
type: String
|
|
- name: options
|
|
isOptional: true
|
|
type: ResetPasswordOptions
|
|
description: >
|
|
`redirectTo`, the URL that the reset link opens, and `captchaToken`.
|
|
examples:
|
|
- id: reset-password
|
|
name: Reset password
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
try await supabase.auth.resetPassword(
|
|
email: "example@email.com",
|
|
options: ResetPasswordOptions(
|
|
redirectTo: URL(string: "my-app-scheme://callback")!
|
|
)
|
|
)
|
|
```
|
|
- id: reset-password-handle-redirect
|
|
name: Show the update password screen
|
|
description: |
|
|
React to the redirect result, or to the `.passwordRecovery` event, to show a screen where the user sets a new password.
|
|
code: |
|
|
```swift
|
|
.onOpenURL { url in
|
|
Task {
|
|
if case .signedIn(_, verification: .recovery)? = try await supabase.handleRedirect(url) {
|
|
isPasswordRecovery = true
|
|
}
|
|
}
|
|
}
|
|
|
|
// Then, when the user submits the new password:
|
|
try await supabase.auth.updateUser(UpdateUser(password: newPassword))
|
|
```
|
|
- id: verify-otp
|
|
title: 'verifyOTP()'
|
|
overwriteParams:
|
|
- name: email
|
|
isOptional: true
|
|
type: String
|
|
description: One of `phone`, `email`, or `tokenHash` must be provided.
|
|
- name: phone
|
|
isOptional: true
|
|
type: String
|
|
description: One of `phone`, `email`, or `tokenHash` must be provided.
|
|
- name: tokenHash
|
|
isOptional: true
|
|
type: String
|
|
description: >
|
|
The token hash from the user's email link.
|
|
One of `phone`, `email`, or `tokenHash` must be provided.
|
|
- name: type
|
|
type: EmailOTPType | PhoneOTPType
|
|
- name: token
|
|
isOptional: true
|
|
type: String
|
|
description: The OTP sent to the user. Required if using `phone` or `email`.
|
|
notes: |
|
|
- 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.
|
|
examples:
|
|
- id: verify-sms-one-time-password(otp)
|
|
name: Verify Sms One-Time Password (OTP)
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let session = try await supabase.auth.verifyOTP(
|
|
phone: "+13334445555",
|
|
token: "123456",
|
|
type: .sms
|
|
)
|
|
```
|
|
- id: verify-signup-one-time-password(otp)
|
|
name: Verify Signup One-Time Password (OTP)
|
|
isSpotlight: false
|
|
code: |
|
|
```swift
|
|
let result = try await supabase.auth.verifyOTP(
|
|
email: "example@example-email.com",
|
|
token: "123456",
|
|
type: .signup
|
|
)
|
|
```
|
|
- id: verify-email-auth(tokenhash)
|
|
name: Verify Email Auth (Token Hash)
|
|
isSpotlight: false
|
|
code: |
|
|
```swift
|
|
switch try await supabase.auth.verifyOTP(tokenHash: tokenHash, type: .emailChange) {
|
|
case .signedIn(let session):
|
|
print(session.user.email ?? "")
|
|
case .emailChangePending(let message):
|
|
print(message)
|
|
}
|
|
```
|
|
- id: get-session
|
|
title: 'session()'
|
|
description: |
|
|
- 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.
|
|
examples:
|
|
- id: get-the-session-data
|
|
name: Get the session data
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let session = try await supabase.auth.session()
|
|
```
|
|
- id: get-current-session-no-validation
|
|
name: Get the current session without validation
|
|
isSpotlight: true
|
|
description: |
|
|
Reading `currentSession` does no I/O, so the session may be expired. It is `nil` until the client has read storage. Call `await supabase.auth.initialization()` first at launch.
|
|
code: |
|
|
```swift
|
|
let session = supabase.auth.currentSession
|
|
```
|
|
- id: get-user
|
|
title: 'user()'
|
|
description: |
|
|
- 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.
|
|
examples:
|
|
- id: get-the-logged-in-user-with-the-current-existing-session
|
|
name: Get the logged in user with the current existing session
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let user = try await supabase.auth.user()
|
|
```
|
|
- id: get-the-logged-in-user-with-a-custom-access-token-jwt
|
|
name: Get the logged in user with a custom access token jwt
|
|
isSpotlight: false
|
|
code: |
|
|
```swift
|
|
let user = try await supabase.auth.user(jwt: "custom-jwt")
|
|
```
|
|
- id: get-current-user
|
|
name: Get current user
|
|
isSpotlight: true
|
|
description: The user returned by this property may be outdated.
|
|
code: |
|
|
```swift
|
|
let user = supabase.auth.currentUser
|
|
```
|
|
- id: update-user
|
|
title: 'updateUser()'
|
|
notes: |
|
|
- 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](https://supabase.com/dashboard/project/_/auth/providers).
|
|
- 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.
|
|
examples:
|
|
- id: update-the-email-for-an-authenticated-user
|
|
name: Update the email for an authenticated user
|
|
description: Sends a "Confirm Email Change" email to the new email address.
|
|
isSpotlight: false
|
|
code: |
|
|
```swift
|
|
try await supabase.auth.updateUser(
|
|
UpdateUser(email: "new@email.com"),
|
|
redirectTo: URL(string: "my-app-scheme://callback")!
|
|
)
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"id": "11111111-1111-1111-1111-111111111111",
|
|
"aud": "authenticated",
|
|
"role": "authenticated",
|
|
"email": "example@email.com",
|
|
"email_confirmed_at": "2024-01-01T00:00:00Z",
|
|
"phone": "",
|
|
"confirmed_at": "2024-01-01T00:00:00Z",
|
|
"new_email": "new@email.com",
|
|
"email_change_sent_at": "2024-01-01T00:00:00Z",
|
|
"last_sign_in_at": "2024-01-01T00:00:00Z",
|
|
"app_metadata": {
|
|
"provider": "email",
|
|
"providers": [
|
|
"email"
|
|
]
|
|
},
|
|
"user_metadata": {
|
|
"email": "example@email.com",
|
|
"email_verified": false,
|
|
"phone_verified": false,
|
|
"sub": "11111111-1111-1111-1111-111111111111"
|
|
},
|
|
"identities": [
|
|
{
|
|
"identity_id": "22222222-2222-2222-2222-222222222222",
|
|
"id": "11111111-1111-1111-1111-111111111111",
|
|
"user_id": "11111111-1111-1111-1111-111111111111",
|
|
"identity_data": {
|
|
"email": "example@email.com",
|
|
"email_verified": false,
|
|
"phone_verified": false,
|
|
"sub": "11111111-1111-1111-1111-111111111111"
|
|
},
|
|
"provider": "email",
|
|
"last_sign_in_at": "2024-01-01T00:00:00Z",
|
|
"created_at": "2024-01-01T00:00:00Z",
|
|
"updated_at": "2024-01-01T00:00:00Z",
|
|
"email": "example@email.com"
|
|
}
|
|
],
|
|
"created_at": "2024-01-01T00:00:00Z",
|
|
"updated_at": "2024-01-01T00:00:00Z",
|
|
"is_anonymous": false
|
|
}
|
|
```
|
|
- id: update-the-phone-for-an-authenticated-user
|
|
name: Update the phone number for an authenticated user
|
|
description: Sends a one-time password (OTP) to the new phone number.
|
|
isSpotlight: false
|
|
code: |
|
|
```swift
|
|
try await supabase.auth.updateUser(
|
|
UpdateUser(phone: "123456789")
|
|
)
|
|
```
|
|
- id: update-the-password-for-an-authenticated-user
|
|
name: Update the password for an authenticated user
|
|
isSpotlight: false
|
|
code: |
|
|
```swift
|
|
try await supabase.auth.updateUser(UpdateUser(password: "newPassw0rd?"))
|
|
```
|
|
- id: update-the-users-metadata
|
|
name: Update the user's metadata
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
try await supabase.auth.updateUser(
|
|
UpdateUser(
|
|
userMetadata: [
|
|
"hello": .string("world")
|
|
]
|
|
)
|
|
)
|
|
```
|
|
- id: update-password-with-reauthentication
|
|
name: Update the user's password with a nonce
|
|
description: |
|
|
If **Secure password change** is enabled in your [project's email provider settings](/dashboard/project/_/auth/providers), updating the user's password would require a nonce if the user **hasn't recently signed in**. The nonce is sent to the user's email or phone number. A user is deemed recently signed in if the session was created in the last 24 hours.
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
try await supabase.auth.updateUser(
|
|
UpdateUser(
|
|
password: "new password",
|
|
nonce: "123456"
|
|
)
|
|
)
|
|
```
|
|
- id: get-user-identities
|
|
title: 'identities()'
|
|
notes: |
|
|
- 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`.
|
|
examples:
|
|
- id: get-user-identities
|
|
name: Returns a list of identities linked to the user
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let identities = try await supabase.auth.identities()
|
|
```
|
|
- id: link-identity
|
|
title: 'linkIdentity()'
|
|
notes: |
|
|
- The **Enable Manual Linking** option must be enabled from your [project's authentication settings](/dashboard/project/_/auth/providers).
|
|
- 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.
|
|
examples:
|
|
- id: link-identity
|
|
name: Link an identity to a user
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let session = try await supabase.auth.linkIdentity(
|
|
.google,
|
|
options: OAuthOptions(redirectTo: URL(string: "my-app-scheme://callback")!)
|
|
)
|
|
```
|
|
description: |
|
|
On Apple platforms, the default presenter is `ASWebAuthenticationSessionPresenter`. On other platforms, pass a presenter.
|
|
- id: link-identity-custom-urlopener
|
|
name: Link an identity to a user with custom URL opening logic
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let session = try await supabase.auth.linkIdentity(
|
|
.google,
|
|
presenter: ClosurePresenter { url, callbackScheme in
|
|
// custom URL opening logic
|
|
// return the callback URL
|
|
return resultURL
|
|
}
|
|
)
|
|
```
|
|
- id: link-identity-with-id-token
|
|
title: 'linkIdentity(idToken:)'
|
|
notes: |
|
|
- The **Enable Manual Linking** option must be enabled from your [project's authentication settings](/dashboard/project/_/auth/providers).
|
|
- The user needs to be signed in to call `linkIdentity(idToken:)`.
|
|
- If the candidate identity is already linked to the existing user or another user, `linkIdentity(idToken:)` will fail.
|
|
- This method allows you to link an OIDC identity using an ID token obtained from a provider like Apple, Google, etc.
|
|
- The client stores the returned session and emits `.userUpdated`.
|
|
examples:
|
|
- id: link-identity-with-id-token
|
|
name: Link an OIDC identity using an ID token
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
try await supabase.auth.linkIdentity(
|
|
idToken: IDTokenCredentials(
|
|
provider: .apple,
|
|
idToken: idToken
|
|
)
|
|
)
|
|
```
|
|
description: |
|
|
Link an OpenID Connect identity to the current user using an ID token. This is useful when you've obtained an ID token from a provider's SDK (like Sign in with Apple) and want to link it to the current user's account.
|
|
- id: link-identity-with-id-token-and-nonce
|
|
name: Link an OIDC identity with nonce
|
|
code: |
|
|
```swift
|
|
let nonce = Nonce.generate()
|
|
// Pass nonce.hashed to the provider.
|
|
|
|
try await supabase.auth.linkIdentity(
|
|
idToken: IDTokenCredentials(
|
|
provider: .apple,
|
|
idToken: idToken,
|
|
nonce: nonce.raw
|
|
)
|
|
)
|
|
```
|
|
description: |
|
|
For providers that support nonce verification (like Apple), you can include the nonce used during authentication.
|
|
- id: unlink-identity
|
|
title: 'unlinkIdentity()'
|
|
notes: |
|
|
- The **Enable Manual Linking** option must be enabled from your [project's authentication settings](/dashboard/project/_/auth/providers).
|
|
- 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.
|
|
examples:
|
|
- id: unlink-identity
|
|
name: Unlink an identity
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
// retrieve all identities linked to a user
|
|
let identities = try await supabase.auth.identities()
|
|
|
|
// find the google identity
|
|
if let googleIdentity = identities.first(where: { $0.provider == .google }) {
|
|
// unlink the google identity
|
|
try await supabase.auth.unlinkIdentity(googleIdentity)
|
|
}
|
|
```
|
|
- id: send-password-reauthentication
|
|
title: 'reauthenticate()'
|
|
notes: |
|
|
- 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](/dashboard/project/_/auth/providers).
|
|
- 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:)`.
|
|
examples:
|
|
- id: send-reauthentication-nonce
|
|
name: Send reauthentication nonce
|
|
description: Sends a reauthentication nonce to the user's email or phone number.
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
try await supabase.auth.reauthenticate()
|
|
```
|
|
- id: resend-email-or-phone-otps
|
|
title: 'resend()'
|
|
notes: |
|
|
- 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.
|
|
examples:
|
|
- id: resend-email-signup-confirmation
|
|
name: Resend an email signup confirmation
|
|
description: Resends the email signup confirmation to the user
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
try await supabase.auth.resend(
|
|
email: "email@example.com",
|
|
type: .signup,
|
|
options: ResendEmailOptions(
|
|
redirectTo: URL(string: "my-app-scheme://callback")!
|
|
)
|
|
)
|
|
```
|
|
- id: resend-phone-signup-confirmation
|
|
name: Resend a phone signup confirmation
|
|
description: Resends the phone signup confirmation email to the user
|
|
code: |
|
|
```swift
|
|
try await supabase.auth.resend(
|
|
phone: "1234567890",
|
|
type: .sms
|
|
)
|
|
```
|
|
- id: resend-email-change-email
|
|
name: Resend email change email
|
|
description: Resends the email change email to the user
|
|
code: |
|
|
```swift
|
|
try await supabase.auth.resend(
|
|
email: "email@example.com",
|
|
type: .emailChange
|
|
)
|
|
```
|
|
- id: resend-phone-change
|
|
name: Resend phone change OTP
|
|
description: Resends the phone change OTP to the user
|
|
code: |
|
|
```swift
|
|
try await supabase.auth.resend(
|
|
phone: "1234567890",
|
|
type: .phoneChange
|
|
)
|
|
```
|
|
- id: set-session
|
|
title: 'importSession()'
|
|
notes: |
|
|
- `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](/docs/guides/local-development/cli/config#auth.enable_refresh_token_rotation) is enabled by default on all projects to guard against replay attacks.
|
|
- You can configure the [`REFRESH_TOKEN_REUSE_INTERVAL`](/docs/guides/local-development/cli/config#auth.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.
|
|
examples:
|
|
- id: refresh-the-session
|
|
name: Import a session
|
|
description: Signs in with the access and refresh tokens and returns the stored session, or throws an error if the tokens are invalid.
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let session = try await supabase.auth.importSession(
|
|
accessToken: "access_token",
|
|
refreshToken: "refresh_token"
|
|
)
|
|
```
|
|
- id: refresh-session
|
|
title: 'refreshSession()'
|
|
notes: |
|
|
- 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:)`.
|
|
examples:
|
|
- id: refresh-session-using-the-current-session
|
|
name: Refresh session using the current session
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let session = try await supabase.auth.refreshSession()
|
|
```
|
|
- id: refresh-session-if-needed
|
|
name: Refresh the session only when needed
|
|
isSpotlight: false
|
|
description: |
|
|
`refreshSessionIfNeeded()` refreshes when less than half of the session's lifetime is left, and returns `nil` when no user is signed in. Call it from a `BGAppRefreshTask` handler.
|
|
code: |
|
|
```swift
|
|
let session = try await supabase.auth.refreshSessionIfNeeded()
|
|
```
|
|
|
|
- id: get-claims
|
|
title: 'claims()'
|
|
notes: |
|
|
- 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.
|
|
overwriteParams:
|
|
- name: jwt
|
|
isOptional: true
|
|
type: String
|
|
description: >
|
|
The JWT to verify. Use `claims(options:)` to verify the access token from the current session.
|
|
- name: options
|
|
isOptional: true
|
|
type: ClaimsOptions
|
|
description: >
|
|
Options for JWT verification. Can specify `allowsExpired` to skip expiration check and `jwks` to provide custom JSON Web Key Set.
|
|
examples:
|
|
- id: get-claims-current-session
|
|
name: Verify and get claims from current session
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let claims = try await supabase.auth.claims()
|
|
print("User ID: \(claims.subject)")
|
|
print("Email: \(claims.email ?? "N/A")")
|
|
print("Role: \(claims.role ?? "N/A")")
|
|
```
|
|
- id: get-claims-custom-jwt
|
|
name: Verify and get claims from a specific JWT
|
|
isSpotlight: false
|
|
code: |
|
|
```swift
|
|
let customToken = "eyJhbGci..."
|
|
let claims = try await supabase.auth.claims(jwt: customToken)
|
|
```
|
|
- id: get-claims-allow-expired
|
|
name: Get claims from an expired JWT
|
|
description: Useful for testing or extracting information from expired tokens.
|
|
isSpotlight: false
|
|
code: |
|
|
```swift
|
|
let claims = try await supabase.auth.claims(
|
|
options: ClaimsOptions(allowsExpired: true)
|
|
)
|
|
```
|
|
- id: get-claims-custom-jwks
|
|
name: Verify JWT with custom JWKS
|
|
description: Provide a custom JSON Web Key Set for verification.
|
|
isSpotlight: false
|
|
code: |
|
|
```swift
|
|
let customJWKS = JWKS(keys: myKeys)
|
|
let claims = try await supabase.auth.claims(
|
|
options: ClaimsOptions(jwks: customJWKS)
|
|
)
|
|
```
|
|
|
|
- id: start-auto-refresh
|
|
title: 'startAutoRefresh()'
|
|
description: |
|
|
Resumes the automatic session refresh process after `stopAutoRefresh()`.
|
|
notes: |
|
|
- 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.
|
|
examples:
|
|
- id: start-auto-refresh
|
|
name: Start automatic session refresh
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
await supabase.auth.startAutoRefresh()
|
|
```
|
|
|
|
- id: stop-auto-refresh
|
|
title: 'stopAutoRefresh()'
|
|
description: |
|
|
Stops the automatic session refresh process until the next `startAutoRefresh()`.
|
|
notes: |
|
|
- 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.
|
|
examples:
|
|
- id: stop-auto-refresh
|
|
name: Stop automatic session refresh
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
await supabase.auth.stopAutoRefresh()
|
|
```
|
|
|
|
- id: exchange-code-for-session
|
|
title: 'exchangeCodeForSession()'
|
|
notes: |
|
|
- 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.
|
|
examples:
|
|
- id: exchange-auth-code
|
|
name: Exchange Auth Code
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let session = try await supabase.auth.exchangeCodeForSession(
|
|
"34e770dd-9ff9-416c-87fa-43b31d7ef225",
|
|
flowID: flow.id
|
|
)
|
|
```
|
|
- id: auth-mfa-api
|
|
title: 'Overview'
|
|
notes: |
|
|
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](/docs/reference/swift/v3/auth-passkey-api) 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()`](/docs/reference/swift/v3/auth-mfa-generaterecoverycodes).
|
|
|
|
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.
|
|
- id: mfa-enroll
|
|
title: 'mfa.enrollTOTP()'
|
|
notes: |
|
|
- 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()`](/docs/reference/swift/v3/auth-mfa-challenge).
|
|
- To verify a challenge, see [`mfa.verify()`](/docs/reference/swift/v3/auth-mfa-verify).
|
|
- To create and verify a challenge in a single step, see [`mfa.challengeAndVerify()`](/docs/reference/swift/v3/auth-mfa-challengeandverify).
|
|
- For WebAuthn, `mfa.enrollWebAuthn(friendlyName:anchor:)` runs the full ceremony and returns the upgraded session (**experimental**). It is not available on watchOS.
|
|
|
|
examples:
|
|
- id: enroll-totp-factor
|
|
name: Enroll a time-based, one-time password (TOTP) factor
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
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
|
|
```
|
|
- id: enroll-phone-factor
|
|
name: Enroll a phone factor
|
|
code: |
|
|
```swift
|
|
let enrollment = try await supabase.auth.mfa.enrollPhone(
|
|
"+15555550100",
|
|
friendlyName: "Work phone"
|
|
)
|
|
|
|
// Send a code to the phone, then verify it with mfa.verify().
|
|
let challenge = try await supabase.auth.mfa.challenge(factorID: enrollment.id)
|
|
```
|
|
- id: enroll-webauthn-factor
|
|
name: Enroll a WebAuthn (passkey) factor (experimental)
|
|
code: |
|
|
```swift
|
|
// @_spi(Experimental) import Supabase
|
|
// enrollWebAuthn runs the full ceremony: enroll, challenge, show the passkey sheet, verify.
|
|
// A nil anchor uses the app's key window.
|
|
let session = try await supabase.auth.mfa.enrollWebAuthn(
|
|
friendlyName: "My passkey"
|
|
)
|
|
```
|
|
- id: mfa-challenge
|
|
title: 'mfa.challenge()'
|
|
notes: |
|
|
- An [enrolled factor](/docs/reference/swift/v3/auth-mfa-enroll) 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()`](/docs/reference/swift/v3/auth-mfa-verify).
|
|
- `expiresAt` is a `Date`.
|
|
examples:
|
|
- id: create-mfa-challenge
|
|
name: Create a challenge for a factor
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let challenge = try await supabase.auth.mfa.challenge(
|
|
factorID: UUID(uuidString: "34e770dd-9ff9-416c-87fa-43b31d7ef225")!
|
|
)
|
|
let challengeID = challenge.id
|
|
let expiresAt = challenge.expiresAt
|
|
```
|
|
- id: create-mfa-challenge-whatsapp
|
|
name: Send the code for a phone factor through WhatsApp
|
|
code: |
|
|
```swift
|
|
let challenge = try await supabase.auth.mfa.challenge(
|
|
factorID: factor.id,
|
|
channel: .whatsapp
|
|
)
|
|
```
|
|
- id: mfa-verify
|
|
title: 'mfa.verify()'
|
|
notes: |
|
|
- To verify a challenge, please [create a challenge](/docs/reference/swift/v3/auth-mfa-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.
|
|
examples:
|
|
- id: verify-challenge
|
|
name: Verify a challenge for a factor
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
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"
|
|
)
|
|
```
|
|
- id: verify-webauthn-factor
|
|
name: Verify a WebAuthn factor (experimental)
|
|
code: |
|
|
```swift
|
|
// @_spi(Experimental) import Supabase
|
|
// verifyWebAuthn runs the full ceremony: challenge, show the passkey sheet, verify.
|
|
// If the user dismisses the sheet, it throws CancellationError.
|
|
let session = try await supabase.auth.mfa.verifyWebAuthn(
|
|
factorID: factor.id
|
|
)
|
|
```
|
|
- id: mfa-challenge-and-verify
|
|
title: 'mfa.challengeAndVerify()'
|
|
notes: |
|
|
- An [enrolled factor](/docs/reference/swift/v3/auth-mfa-enroll) is required before invoking `challengeAndVerify()`.
|
|
- Executes [`mfa.challenge()`](/docs/reference/swift/v3/auth-mfa-challenge) and [`mfa.verify()`](/docs/reference/swift/v3/auth-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.
|
|
examples:
|
|
- id: challenge-and-verify
|
|
name: Create and verify a challenge for a factor
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let session = try await supabase.auth.mfa.challengeAndVerify(
|
|
factorID: UUID(uuidString: "34e770dd-9ff9-416c-87fa-43b31d7ef225")!,
|
|
code: "123456"
|
|
)
|
|
```
|
|
- id: mfa-unenroll
|
|
title: 'mfa.unenroll()'
|
|
notes: |
|
|
- The session must be at `aal2` to remove a `verified` factor.
|
|
- To remove the recovery codes factor, use [`mfa.recoveryCodes.unenroll()`](/docs/reference/swift/v3/auth-mfa-unenrollrecoverycodes).
|
|
examples:
|
|
- id: unenroll-a-factor
|
|
name: Unenroll a factor
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let response = try await supabase.auth.mfa.unenroll(
|
|
factorID: UUID(uuidString: "34e770dd-9ff9-416c-87fa-43b31d7ef225")!
|
|
)
|
|
print(response.id) // ID of the unenrolled factor
|
|
```
|
|
- id: mfa-get-authenticator-assurance-level
|
|
title: 'mfa.assuranceLevel()'
|
|
notes: |
|
|
- 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`.
|
|
examples:
|
|
- id: get-aal
|
|
name: Get the AAL details of a session
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let aal = try await supabase.auth.mfa.assuranceLevel()
|
|
let currentLevel = aal.currentLevel
|
|
let nextLevel = aal.nextLevel
|
|
let currentAuthenticationMethods = aal.currentAuthenticationMethods
|
|
```
|
|
- id: prompt-for-mfa
|
|
name: Ask for a second factor when one is needed
|
|
code: |
|
|
```swift
|
|
do {
|
|
let aal = try await supabase.auth.mfa.assuranceLevel()
|
|
if aal.nextLevel != aal.currentLevel {
|
|
// Show the MFA prompt.
|
|
}
|
|
} catch let error as AuthError where error.kind == .sessionMissing {
|
|
// Show the sign-in screen.
|
|
}
|
|
```
|
|
- id: auth-js-gotruemfaapi-listfactors
|
|
title: 'mfa.factors()'
|
|
notes: |
|
|
- 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.
|
|
examples:
|
|
- id: list-factors
|
|
name: List all factors for a user
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let factors = try await supabase.auth.mfa.factors()
|
|
let verified = factors.verified
|
|
let unverified = factors.unverified
|
|
```
|
|
- id: list-verified-totp-factors
|
|
name: List the verified TOTP factors
|
|
code: |
|
|
```swift
|
|
let totpFactors = try await supabase.auth.mfa.factors().verified
|
|
.filter { $0.factorType == .totp }
|
|
```
|
|
- id: mfa-get-recovery-codes-status
|
|
title: 'mfa.recoveryCodes.status()'
|
|
notes: |
|
|
- 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.
|
|
examples:
|
|
- id: get-recovery-codes-status
|
|
name: Get the status of the recovery codes
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let status = try await supabase.auth.mfa.recoveryCodes.status()
|
|
print("\(status.remaining) of \(status.total) codes left")
|
|
```
|
|
- id: mfa-generate-recovery-codes
|
|
title: 'mfa.recoveryCodes.generate()'
|
|
notes: |
|
|
- 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()`](/docs/reference/swift/v3/auth-mfa-regeneraterecoverycodes).
|
|
- Recovery codes are an experimental Supabase Auth feature. Enable them on the Auth server first.
|
|
examples:
|
|
- id: generate-recovery-codes
|
|
name: Generate recovery codes
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let generated = try await supabase.auth.mfa.recoveryCodes.generate(
|
|
friendlyName: "Backup codes"
|
|
)
|
|
// Show generated.codes to the user once.
|
|
let codes = generated.codes
|
|
```
|
|
- id: mfa-regenerate-recovery-codes
|
|
title: 'mfa.recoveryCodes.regenerate()'
|
|
notes: |
|
|
- 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.
|
|
examples:
|
|
- id: regenerate-recovery-codes
|
|
name: Regenerate recovery codes
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let regenerated = try await supabase.auth.mfa.recoveryCodes.regenerate()
|
|
let codes = regenerated.codes
|
|
```
|
|
- id: mfa-verify-recovery-code
|
|
title: 'mfa.recoveryCodes.verify()'
|
|
notes: |
|
|
- 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.
|
|
examples:
|
|
- id: verify-recovery-code
|
|
name: Verify a recovery code
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let session = try await supabase.auth.mfa.recoveryCodes.verify(
|
|
code: "K4M9-X7QP-2AB8-HT3Z"
|
|
)
|
|
```
|
|
- id: mfa-unenroll-recovery-codes
|
|
title: 'mfa.recoveryCodes.unenroll()'
|
|
notes: |
|
|
- Removes the recovery codes factor and every code in it.
|
|
- The session must be at `aal2`.
|
|
examples:
|
|
- id: unenroll-recovery-codes
|
|
name: Remove the recovery codes
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let response = try await supabase.auth.mfa.recoveryCodes.unenroll()
|
|
print(response.id) // ID of the removed factor
|
|
```
|
|
- id: passkey-api
|
|
title: 'Overview'
|
|
notes: |
|
|
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.
|
|
- id: passkey-list
|
|
title: 'passkeys.list()'
|
|
notes: |
|
|
Returns the list of passkeys registered to the signed-in user.
|
|
examples:
|
|
- id: list-passkeys
|
|
name: List the current user's passkeys
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
// @_spi(Experimental) import Supabase
|
|
let passkeys: [PasskeyListItem] = try await supabase.auth.passkeys.list()
|
|
```
|
|
- id: passkey-update
|
|
title: 'passkeys.rename(id:friendlyName:)'
|
|
notes: |
|
|
Updates the friendly name of a passkey. Limited to 120 characters.
|
|
params:
|
|
- name: id
|
|
isOptional: false
|
|
type: UUID
|
|
description: ID of the passkey to rename.
|
|
- name: friendlyName
|
|
isOptional: false
|
|
type: String
|
|
description: New human readable name. Limited to 120 characters.
|
|
examples:
|
|
- id: rename-passkey
|
|
name: Rename a passkey
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
// @_spi(Experimental) import Supabase
|
|
let passkey = try await supabase.auth.passkeys.rename(
|
|
id: UUID(uuidString: "34e770dd-9ff9-416c-87fa-43b31d7ef225")!,
|
|
friendlyName: "Work laptop"
|
|
)
|
|
```
|
|
- id: passkey-delete
|
|
title: 'passkeys.delete(id:)'
|
|
notes: |
|
|
Removes a passkey from the signed-in user's account.
|
|
params:
|
|
- name: id
|
|
isOptional: false
|
|
type: UUID
|
|
description: ID of the passkey to delete.
|
|
examples:
|
|
- id: delete-passkey
|
|
name: Delete a passkey
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
// @_spi(Experimental) import Supabase
|
|
try await supabase.auth.passkeys.delete(
|
|
id: UUID(uuidString: "34e770dd-9ff9-416c-87fa-43b31d7ef225")!
|
|
)
|
|
```
|
|
- id: passkey-start-registration
|
|
title: 'passkeys.registrationOptions()'
|
|
notes: |
|
|
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`.
|
|
examples:
|
|
- id: start-passkey-registration
|
|
name: Get passkey registration options
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
// @_spi(Experimental) import Supabase
|
|
let options: PasskeyRegistrationOptions = try await supabase.auth.passkeys.registrationOptions()
|
|
// Hand options.options to the platform authenticator.
|
|
```
|
|
- id: passkey-verify-registration
|
|
title: 'passkeys.verifyRegistration(challengeID:credential:)'
|
|
notes: |
|
|
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:)`.
|
|
params:
|
|
- name: challengeID
|
|
isOptional: false
|
|
type: UUID
|
|
description: The `challengeID` returned by `passkeys.registrationOptions()`.
|
|
- name: credential
|
|
isOptional: false
|
|
type: JSONValue
|
|
description: The W3C `PublicKeyCredential` JSON produced by the authenticator.
|
|
examples:
|
|
- id: verify-passkey-registration
|
|
name: Verify a passkey registration
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
// @_spi(Experimental) import Supabase
|
|
let passkey: PasskeyListItem = try await supabase.auth.passkeys.verifyRegistration(
|
|
challengeID: options.challengeID,
|
|
credential: credential
|
|
)
|
|
```
|
|
- id: passkey-start-authentication
|
|
title: 'passkeys.authenticationOptions()'
|
|
notes: |
|
|
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:)`.
|
|
examples:
|
|
- id: start-passkey-authentication
|
|
name: Get passkey authentication options
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
// @_spi(Experimental) import Supabase
|
|
let options: PasskeyAuthenticationOptions = try await supabase.auth.passkeys.authenticationOptions()
|
|
// Hand options.options to the platform authenticator.
|
|
```
|
|
- id: passkey-verify-authentication
|
|
title: 'passkeys.verifyAuthentication(challengeID:credential:)'
|
|
notes: |
|
|
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`.
|
|
params:
|
|
- name: challengeID
|
|
isOptional: false
|
|
type: UUID
|
|
description: The `challengeID` returned by `passkeys.authenticationOptions()`.
|
|
- name: credential
|
|
isOptional: false
|
|
type: JSONValue
|
|
description: The W3C `PublicKeyCredential` JSON produced by the authenticator.
|
|
examples:
|
|
- id: verify-passkey-authentication
|
|
name: Verify a passkey sign in
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
// @_spi(Experimental) import Supabase
|
|
let session: Session = try await supabase.auth.passkeys.verifyAuthentication(
|
|
challengeID: options.challengeID,
|
|
credential: credential
|
|
)
|
|
let user = session.user
|
|
```
|
|
- id: admin-api
|
|
title: 'Overview'
|
|
notes: |
|
|
- 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.
|
|
examples:
|
|
- id: create-auth-admin-client
|
|
name: Create server-side auth client
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
import Supabase
|
|
|
|
let admin = AuthAdminClient(
|
|
configuration: .init(
|
|
url: supabaseURL.appendingPathComponent("auth/v1"),
|
|
secretKey: secretKey
|
|
)
|
|
)
|
|
```
|
|
- id: delete-user
|
|
title: 'deleteUser()'
|
|
notes: |
|
|
- 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.
|
|
examples:
|
|
- id: removes-a-user
|
|
name: Removes a user
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
try await admin.deleteUser(
|
|
id: UUID(uuidString: "715ed5db-f090-4b8c-a067-640ecee36aa0")!
|
|
)
|
|
```
|
|
- id: soft-deletes-a-user
|
|
name: Soft-delete a user
|
|
code: |
|
|
```swift
|
|
try await admin.deleteUser(
|
|
id: UUID(uuidString: "715ed5db-f090-4b8c-a067-640ecee36aa0")!,
|
|
softDelete: true
|
|
)
|
|
```
|
|
|
|
- id: get-user-by-id
|
|
title: 'user(id:)'
|
|
description: |
|
|
Get user by ID.
|
|
notes: |
|
|
- The `user(id:)` method requires a user's ID.
|
|
examples:
|
|
- id: get-user-by-id
|
|
name: Get user by ID
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let user = try await admin.user(
|
|
id: UUID(uuidString: "715ed5db-f090-4b8c-a067-640ecee36aa0")!
|
|
)
|
|
```
|
|
|
|
- id: list-users
|
|
title: 'listUsers()'
|
|
description: |
|
|
List all users in the system.
|
|
notes: |
|
|
- `listUsers(page:pageSize:)` returns one `UserPage`. Pages start at `1`.
|
|
- To walk every page, iterate `users(pageSize:)`. It fetches each page as you go.
|
|
examples:
|
|
- id: list-users
|
|
name: List users
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let page = try await admin.listUsers()
|
|
let users = page.users
|
|
```
|
|
- id: list-users-with-pagination
|
|
name: List users with pagination
|
|
code: |
|
|
```swift
|
|
let page = try await admin.listUsers(
|
|
page: 2,
|
|
pageSize: 10
|
|
)
|
|
let users = page.users
|
|
let total = page.total
|
|
```
|
|
- id: list-all-users
|
|
name: Iterate over every user
|
|
code: |
|
|
```swift
|
|
for try await user in admin.users(pageSize: 100) {
|
|
print(user.id)
|
|
}
|
|
```
|
|
|
|
- id: create-user
|
|
title: 'createUser()'
|
|
description: |
|
|
Create a new user.
|
|
notes: |
|
|
- 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:)`.
|
|
examples:
|
|
- id: create-user
|
|
name: Create user
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let user = try await admin.createUser(
|
|
AdminCreateUser(
|
|
email: "user@email.com",
|
|
password: "password",
|
|
confirmsEmail: true
|
|
)
|
|
)
|
|
```
|
|
|
|
- id: update-user-by-id
|
|
title: 'updateUser(id:_:)'
|
|
description: |
|
|
Update user by ID.
|
|
notes: |
|
|
- The server changes only the fields you set in `AdminUpdateUser`.
|
|
- `banDuration` is a `Duration`. Pass `.zero` to lift a ban.
|
|
examples:
|
|
- id: update-user-by-id
|
|
name: Update user by ID
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let user = try await admin.updateUser(
|
|
id: UUID(uuidString: "715ed5db-f090-4b8c-a067-640ecee36aa0")!,
|
|
AdminUpdateUser(
|
|
email: "newemail@email.com"
|
|
)
|
|
)
|
|
```
|
|
- id: ban-user
|
|
name: Ban a user for 24 hours
|
|
code: |
|
|
```swift
|
|
let user = try await admin.updateUser(
|
|
id: UUID(uuidString: "715ed5db-f090-4b8c-a067-640ecee36aa0")!,
|
|
AdminUpdateUser(banDuration: .seconds(86_400))
|
|
)
|
|
```
|
|
|
|
- id: invite-user-by-email
|
|
title: 'inviteUser()'
|
|
description: |
|
|
Send an invite link to the user's email address.
|
|
notes: |
|
|
- `userMetadata` is stored in the user's `user_metadata`.
|
|
- The admin client has no default redirect. Without `redirectTo`, the server uses the site URL.
|
|
examples:
|
|
- id: invite-user-by-email
|
|
name: Invite user by email
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let user = try await admin.inviteUser(
|
|
email: "user@email.com",
|
|
userMetadata: ["role": "admin"],
|
|
redirectTo: URL(string: "https://example.com/welcome")
|
|
)
|
|
```
|
|
|
|
- id: generate-link
|
|
title: 'generateLink()'
|
|
description: |
|
|
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.
|
|
notes: |
|
|
- `GenerateLink` exposes 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 `.signUp` and `.invite` if one doesn't already exist.
|
|
- The admin client has no default redirect. Without `redirectTo`, the server uses the site URL.
|
|
examples:
|
|
- id: generate-a-signup-link
|
|
name: Generate a signup link
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let response = try await admin.generateLink(
|
|
.signUp(
|
|
email: "email@example.com",
|
|
password: "secret"
|
|
)
|
|
)
|
|
|
|
let actionLink = response.properties.actionLink
|
|
let emailOTP = response.properties.emailOTP
|
|
```
|
|
- id: generate-a-recovery-link
|
|
name: Generate a recovery link
|
|
code: |
|
|
```swift
|
|
let response = try await admin.generateLink(
|
|
.recovery(
|
|
email: "email@example.com",
|
|
redirectTo: URL(string: "https://example.com/reset-password")
|
|
)
|
|
)
|
|
```
|
|
|
|
- id: auth-js-gotrueadminapi-signout
|
|
title: 'signOut()'
|
|
description: |
|
|
Signs out a specific user by revoking their session(s), using that user's access token (JWT).
|
|
notes: |
|
|
- 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.
|
|
examples:
|
|
- id: sign-out-a-user
|
|
name: Sign out a user
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
try await admin.signOut(jwt: jwt)
|
|
```
|
|
- id: sign-out-a-user-with-scope
|
|
name: Sign out a user with a scope
|
|
code: |
|
|
```swift
|
|
try await admin.signOut(jwt: jwt, scope: .others)
|
|
```
|
|
|
|
- id: mfa-list-factors-admin
|
|
title: 'mfa.listFactors(forUser:)'
|
|
description: |
|
|
List the MFA factors of a user.
|
|
notes: |
|
|
- Requires `secret` key.
|
|
examples:
|
|
- id: list-factors-admin
|
|
name: List a user's factors
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let factors = try await admin.mfa.listFactors(
|
|
forUser: UUID(uuidString: "715ed5db-f090-4b8c-a067-640ecee36aa0")!
|
|
)
|
|
```
|
|
|
|
- id: mfa-delete-factor
|
|
title: 'mfa.deleteFactor(id:forUser:)'
|
|
description: |
|
|
Delete an MFA factor of a user.
|
|
notes: |
|
|
- Requires `secret` key.
|
|
- The user's sessions drop to `aal1`.
|
|
examples:
|
|
- id: delete-factor-admin
|
|
name: Delete a user's factor
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
try await admin.mfa.deleteFactor(
|
|
id: UUID(uuidString: "34e770dd-9ff9-416c-87fa-43b31d7ef225")!,
|
|
forUser: UUID(uuidString: "715ed5db-f090-4b8c-a067-640ecee36aa0")!
|
|
)
|
|
```
|
|
|
|
- id: admin-passkey-api
|
|
title: 'Overview'
|
|
notes: |
|
|
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.
|
|
|
|
- id: admin-list-passkeys
|
|
title: 'passkeys.list(forUser:)'
|
|
description: |
|
|
List the passkeys of a user.
|
|
examples:
|
|
- id: admin-list-passkeys
|
|
name: List a user's passkeys
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
// @_spi(Experimental) import Supabase
|
|
let passkeys = try await admin.passkeys.list(
|
|
forUser: UUID(uuidString: "715ed5db-f090-4b8c-a067-640ecee36aa0")!
|
|
)
|
|
```
|
|
|
|
- id: admin-delete-passkey
|
|
title: 'passkeys.delete(id:forUser:)'
|
|
description: |
|
|
Delete a passkey of a user.
|
|
examples:
|
|
- id: admin-delete-passkey
|
|
name: Delete a user's passkey
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
// @_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")!
|
|
)
|
|
```
|
|
|
|
- id: admin-create-custom-provider
|
|
title: 'customProviders.create()'
|
|
description: |
|
|
Create a custom OAuth 2.0 or OIDC provider.
|
|
notes: |
|
|
- 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.
|
|
examples:
|
|
- id: create-oidc-provider
|
|
name: Create an OIDC provider
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let provider = try await admin.customProviders.create(
|
|
.oidc(
|
|
identifier: "custom:acme",
|
|
name: "Acme",
|
|
clientID: "client-id",
|
|
clientSecret: "client-secret",
|
|
issuer: "https://auth.acme.com"
|
|
)
|
|
)
|
|
```
|
|
- id: create-oauth2-provider
|
|
name: Create an OAuth 2.0 provider
|
|
code: |
|
|
```swift
|
|
let provider = try await admin.customProviders.create(
|
|
.oauth2(
|
|
identifier: "custom:acme",
|
|
name: "Acme",
|
|
clientID: "client-id",
|
|
clientSecret: "client-secret",
|
|
authorizationURL: URL(string: "https://acme.com/oauth/authorize")!,
|
|
tokenURL: URL(string: "https://acme.com/oauth/token")!,
|
|
userinfoURL: URL(string: "https://acme.com/oauth/userinfo")!
|
|
)
|
|
)
|
|
```
|
|
|
|
- id: admin-get-custom-provider
|
|
title: 'customProviders.provider(identifier:)'
|
|
description: |
|
|
Get a custom provider.
|
|
notes: |
|
|
- Requires `secret` key.
|
|
examples:
|
|
- id: get-custom-provider
|
|
name: Get a custom provider
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let provider = try await admin.customProviders.provider(identifier: "custom:acme")
|
|
```
|
|
|
|
- id: admin-list-custom-providers
|
|
title: 'customProviders.list()'
|
|
description: |
|
|
List the custom providers.
|
|
notes: |
|
|
- Requires `secret` key.
|
|
- Pass `type:` to list only the providers of one type.
|
|
examples:
|
|
- id: list-custom-providers
|
|
name: List all custom providers
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let providers = try await admin.customProviders.list()
|
|
```
|
|
- id: list-oidc-custom-providers
|
|
name: List the OIDC providers
|
|
code: |
|
|
```swift
|
|
let providers = try await admin.customProviders.list(type: .oidc)
|
|
```
|
|
|
|
- id: admin-update-custom-provider
|
|
title: 'customProviders.update(identifier:_:)'
|
|
description: |
|
|
Update a custom provider.
|
|
notes: |
|
|
- 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.
|
|
examples:
|
|
- id: update-custom-provider
|
|
name: Update a custom provider
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let provider = try await admin.customProviders.update(
|
|
identifier: "custom:acme",
|
|
UpdateCustomProvider(
|
|
name: "Acme Corp",
|
|
scopes: ["openid", "email", "profile"]
|
|
)
|
|
)
|
|
```
|
|
|
|
- id: admin-delete-custom-provider
|
|
title: 'customProviders.delete(identifier:)'
|
|
description: |
|
|
Delete a custom provider.
|
|
notes: |
|
|
- Requires `secret` key.
|
|
examples:
|
|
- id: delete-custom-provider
|
|
name: Delete a custom provider
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
try await admin.customProviders.delete(identifier: "custom:acme")
|
|
```
|
|
|
|
- id: oauth-admin-api
|
|
title: 'Overview'
|
|
notes: |
|
|
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.
|
|
|
|
- id: admin-oauth-list-clients
|
|
title: 'oauth.listClients()'
|
|
description: |
|
|
List all OAuth clients.
|
|
notes: |
|
|
- 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.
|
|
examples:
|
|
- id: list-oauth-clients
|
|
name: List all OAuth clients
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let clients = try await admin.oauth.listClients()
|
|
```
|
|
|
|
- id: admin-oauth-create-client
|
|
title: 'oauth.createClient()'
|
|
description: |
|
|
Create a new OAuth client.
|
|
notes: |
|
|
- 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.
|
|
overwriteParams:
|
|
- name: client
|
|
type: CreateOAuthClient
|
|
description: >
|
|
The new client, including its name and redirect URIs.
|
|
examples:
|
|
- id: create-oauth-client
|
|
name: Create a new OAuth client
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
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
|
|
```
|
|
|
|
- id: admin-oauth-get-client
|
|
title: 'oauth.client(id:)'
|
|
description: |
|
|
Get details of a specific OAuth client.
|
|
notes: |
|
|
- Requires `secret` key.
|
|
- This method is part of the OAuth 2.1 server administration API.
|
|
overwriteParams:
|
|
- name: id
|
|
type: UUID
|
|
description: >
|
|
The ID of the OAuth client to retrieve.
|
|
examples:
|
|
- id: get-oauth-client
|
|
name: Get OAuth client by ID
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let client = try await admin.oauth.client(
|
|
id: UUID(uuidString: "12345678-1234-1234-1234-123456789012")!
|
|
)
|
|
```
|
|
|
|
- id: admin-oauth-update-client
|
|
title: 'oauth.updateClient(id:_:)'
|
|
description: |
|
|
Update an OAuth client.
|
|
notes: |
|
|
- 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.
|
|
overwriteParams:
|
|
- name: id
|
|
type: UUID
|
|
description: >
|
|
The ID of the OAuth client to update.
|
|
- name: changes
|
|
type: UpdateOAuthClient
|
|
description: >
|
|
The fields to change.
|
|
examples:
|
|
- id: update-oauth-client
|
|
name: Update an OAuth client
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
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")!]
|
|
)
|
|
)
|
|
```
|
|
|
|
- id: admin-oauth-delete-client
|
|
title: 'oauth.deleteClient(id:)'
|
|
description: |
|
|
Delete an OAuth client.
|
|
notes: |
|
|
- Requires `secret` key.
|
|
- This method is part of the OAuth 2.1 server administration API.
|
|
- This action cannot be undone.
|
|
overwriteParams:
|
|
- name: id
|
|
type: UUID
|
|
description: >
|
|
The ID of the OAuth client to delete.
|
|
examples:
|
|
- id: delete-oauth-client
|
|
name: Delete an OAuth client
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
try await admin.oauth.deleteClient(
|
|
id: UUID(uuidString: "12345678-1234-1234-1234-123456789012")!
|
|
)
|
|
```
|
|
|
|
- id: admin-oauth-regenerate-client-secret
|
|
title: 'oauth.regenerateClientSecret(id:)'
|
|
description: |
|
|
Regenerate the secret for an OAuth client.
|
|
notes: |
|
|
- 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.
|
|
overwriteParams:
|
|
- name: id
|
|
type: UUID
|
|
description: >
|
|
The ID of the OAuth client whose secret should be regenerated.
|
|
examples:
|
|
- id: regenerate-oauth-client-secret
|
|
name: Regenerate OAuth client secret
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
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")
|
|
```
|
|
- id: select
|
|
title: 'Fetch data: select()'
|
|
notes: |
|
|
- 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](/docs/reference/swift/v3/using-modifiers)
|
|
- `select()` can be combined with [Filters](/docs/reference/swift/v3/using-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](https://github.com/supabase/supabase/issues/5465).
|
|
- 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.
|
|
examples:
|
|
- id: getting-your-data
|
|
name: Getting your data
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
struct Instrument: Decodable {
|
|
let id: Int
|
|
let name: String
|
|
}
|
|
|
|
let instruments: [Instrument] = try await supabase
|
|
.from("instruments")
|
|
.select()
|
|
.execute()
|
|
.value
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
instruments (id int8 primary key, name text);
|
|
|
|
insert into
|
|
instruments (id, name)
|
|
values
|
|
(1, 'violin'),
|
|
(2, 'viola'),
|
|
(3, 'cello');
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": [
|
|
{
|
|
"id": 1,
|
|
"name": "violin"
|
|
},
|
|
{
|
|
"id": 2,
|
|
"name": "viola"
|
|
},
|
|
{
|
|
"id": 3,
|
|
"name": "cello"
|
|
}
|
|
],
|
|
"status": 200,
|
|
"statusText": "OK"
|
|
}
|
|
```
|
|
- id: selecting-specific-columns
|
|
name: Selecting specific columns
|
|
code: |
|
|
```swift
|
|
struct Instrument: Decodable {
|
|
let name: String
|
|
}
|
|
|
|
let instruments: [Instrument] = try await supabase
|
|
.from("instruments")
|
|
.select("name")
|
|
.execute()
|
|
.value
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
instruments (id int8 primary key, name text);
|
|
|
|
insert into
|
|
instruments (id, name)
|
|
values
|
|
(1, 'violin'),
|
|
(2, 'viola'),
|
|
(3, 'cello');
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": [
|
|
{
|
|
"name": "violin"
|
|
},
|
|
{
|
|
"name": "viola"
|
|
},
|
|
{
|
|
"name": "cello"
|
|
}
|
|
],
|
|
"status": 200,
|
|
"statusText": "OK"
|
|
}
|
|
```
|
|
- id: query-foreign-tables
|
|
name: Query foreign tables
|
|
description: |
|
|
If your database has foreign key relationships, you can query related tables too.
|
|
code: |
|
|
```swift
|
|
struct OrchestralSection: Decodable {
|
|
let name: String
|
|
let instruments: [Instrument]
|
|
}
|
|
|
|
struct Instrument: Decodable {
|
|
let name: String
|
|
}
|
|
|
|
let orchestralSections: [OrchestralSection] = try await supabase
|
|
.from("orchestral_sections")
|
|
.select(
|
|
"""
|
|
name,
|
|
instruments (
|
|
name
|
|
)
|
|
"""
|
|
)
|
|
.execute()
|
|
.value
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
orchestral_sections (id int8 primary key, name text);
|
|
create table
|
|
instruments (
|
|
id int8 primary key,
|
|
section_id int8 not null references orchestral_sections,
|
|
name text
|
|
);
|
|
|
|
insert into
|
|
orchestral_sections (id, name)
|
|
values
|
|
(1, 'strings'),
|
|
(2, 'woodwinds');
|
|
insert into
|
|
instruments (id, section_id, name)
|
|
values
|
|
(1, 2, 'flute'),
|
|
(2, 1, 'violin');
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": [
|
|
{
|
|
"name": "strings",
|
|
"instruments": [
|
|
{
|
|
"name": "violin"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"name": "woodwinds",
|
|
"instruments": [
|
|
{
|
|
"name": "flute"
|
|
}
|
|
]
|
|
}
|
|
],
|
|
"status": 200,
|
|
"statusText": "OK"
|
|
}
|
|
```
|
|
- id: query-foreign-tables-through-a-join-table
|
|
name: Query foreign tables through a join table
|
|
code: |
|
|
```swift
|
|
struct User: Decodable {
|
|
let name: String
|
|
let teams: [Team]
|
|
}
|
|
|
|
struct Team: Decodable {
|
|
let name: String
|
|
}
|
|
|
|
let users: [User] = try await supabase
|
|
.from("users")
|
|
.select(
|
|
"""
|
|
name,
|
|
teams (
|
|
name
|
|
)
|
|
"""
|
|
)
|
|
.execute()
|
|
.value
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
users (
|
|
id int8 primary key,
|
|
name text
|
|
);
|
|
create table
|
|
teams (
|
|
id int8 primary key,
|
|
name text
|
|
);
|
|
-- join table
|
|
create table
|
|
users_teams (
|
|
user_id int8 not null references users,
|
|
team_id int8 not null references teams,
|
|
-- both foreign keys must be part of a composite primary key
|
|
primary key (user_id, team_id)
|
|
);
|
|
|
|
insert into
|
|
users (id, name)
|
|
values
|
|
(1, 'Kiran'),
|
|
(2, 'Evan');
|
|
insert into
|
|
teams (id, name)
|
|
values
|
|
(1, 'Green'),
|
|
(2, 'Blue');
|
|
insert into
|
|
users_teams (user_id, team_id)
|
|
values
|
|
(1, 1),
|
|
(1, 2),
|
|
(2, 2);
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": [
|
|
{
|
|
"name": "Kiran",
|
|
"teams": [
|
|
{
|
|
"name": "Green"
|
|
},
|
|
{
|
|
"name": "Blue"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"name": "Evan",
|
|
"teams": [
|
|
{
|
|
"name": "Blue"
|
|
}
|
|
]
|
|
}
|
|
],
|
|
"status": 200,
|
|
"statusText": "OK"
|
|
}
|
|
```
|
|
description: |
|
|
If you're in a situation where your tables are **NOT** directly
|
|
related, but instead are joined by a _join table_, you can still use
|
|
the `select()` method to query the related data. The join table needs
|
|
to have the foreign keys as part of its composite primary key.
|
|
hideCodeBlock: true
|
|
- id: query-the-same-foreign-table-multiple-times
|
|
name: Query the same foreign table multiple times
|
|
code: |
|
|
```swift
|
|
struct Message: Decodable {
|
|
let content: String
|
|
let from: User
|
|
let to: User
|
|
}
|
|
|
|
struct User: Decodable {
|
|
let name: String
|
|
}
|
|
|
|
let messages: [Message] = try await supabase
|
|
.from("messages")
|
|
.select(
|
|
"""
|
|
content,
|
|
from:sender_id(name),
|
|
to:receiver_id(name)
|
|
"""
|
|
)
|
|
.execute()
|
|
.value
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
users (id int8 primary key, name text);
|
|
|
|
create table
|
|
messages (
|
|
sender_id int8 not null references users,
|
|
receiver_id int8 not null references users,
|
|
content text
|
|
);
|
|
|
|
insert into
|
|
users (id, name)
|
|
values
|
|
(1, 'Kiran'),
|
|
(2, 'Evan');
|
|
|
|
insert into
|
|
messages (sender_id, receiver_id, content)
|
|
values
|
|
(1, 2, '👋');
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": [
|
|
{
|
|
"content": "👋",
|
|
"from": {
|
|
"name": "Kiran"
|
|
},
|
|
"to": {
|
|
"name": "Evan"
|
|
}
|
|
}
|
|
],
|
|
"status": 200,
|
|
"statusText": "OK"
|
|
}
|
|
```
|
|
description: |
|
|
If you need to query the same foreign table twice, use the name of the
|
|
joined column to identify which join to use. You can also give each
|
|
column an alias.
|
|
hideCodeBlock: true
|
|
- id: filtering-through-foreign-tables
|
|
name: Filtering through foreign tables
|
|
code: |
|
|
```swift
|
|
struct Instrument: Decodable {
|
|
let name: String
|
|
let orchestralSections: OrchestralSection?
|
|
|
|
enum CodingKeys: String, CodingKey {
|
|
case name
|
|
case orchestralSections = "orchestral_sections"
|
|
}
|
|
}
|
|
|
|
struct OrchestralSection: Decodable {
|
|
let name: String
|
|
}
|
|
|
|
let instruments: [Instrument] = try await supabase
|
|
.from("instruments")
|
|
.select("name, orchestral_sections(*)")
|
|
.eq("orchestral_sections.name", value: "percussion")
|
|
.execute()
|
|
.value
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
orchestral_sections (id int8 primary key, name text);
|
|
create table
|
|
instruments (
|
|
id int8 primary key,
|
|
section_id int8 not null references orchestral_sections,
|
|
name text
|
|
);
|
|
|
|
insert into
|
|
orchestral_sections (id, name)
|
|
values
|
|
(1, 'strings'),
|
|
(2, 'woodwinds');
|
|
insert into
|
|
instruments (id, section_id, name)
|
|
values
|
|
(1, 2, 'flute'),
|
|
(2, 1, 'violin');
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": [
|
|
{
|
|
"name": "flute",
|
|
"orchestral_sections": null
|
|
},
|
|
{
|
|
"name": "violin",
|
|
"orchestral_sections": null
|
|
}
|
|
],
|
|
"status": 200,
|
|
"statusText": "OK"
|
|
}
|
|
```
|
|
description: |
|
|
If the filter on a foreign table's column is not satisfied, the foreign
|
|
table returns `[]` or `null` but the parent table is not filtered out.
|
|
If you want to filter out the parent table rows, use the `!inner` hint.
|
|
hideCodeBlock: true
|
|
- id: querying-foreign-table-with-count
|
|
name: Querying foreign table with count
|
|
code: |
|
|
```swift
|
|
struct OrchestralSection: Decodable {
|
|
let id: UUID
|
|
let name: String
|
|
let instruments: [Instrument]
|
|
}
|
|
|
|
struct Instrument: Decodable {
|
|
let count: Int
|
|
}
|
|
|
|
let orchestralSections: [OrchestralSection] = try await supabase
|
|
.from("orchestral_sections")
|
|
.select("*, instruments(count)")
|
|
.execute()
|
|
.value
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table orchestral_sections (
|
|
"id" "uuid" primary key default "extensions"."uuid_generate_v4"() not null,
|
|
"name" text
|
|
);
|
|
|
|
create table instruments (
|
|
"id" "uuid" primary key default "extensions"."uuid_generate_v4"() not null,
|
|
"name" text,
|
|
"section_id" "uuid" references public.orchestral_sections on delete cascade
|
|
);
|
|
|
|
with section as (
|
|
insert into orchestral_sections (name)
|
|
values ('strings') returning id
|
|
)
|
|
insert into instruments (name, section_id) values
|
|
('violin', (select id from section)),
|
|
('viola', (select id from section)),
|
|
('cello', (select id from section)),
|
|
('double bass', (select id from section));
|
|
```
|
|
response: |
|
|
```json
|
|
[
|
|
{
|
|
"id": "693694e7-d993-4360-a6d7-6294e325d9b6",
|
|
"name": "strings",
|
|
"instruments": [
|
|
{
|
|
"count": 4
|
|
}
|
|
]
|
|
}
|
|
]
|
|
```
|
|
description: |
|
|
You can get the number of rows in a related table by using the
|
|
**count** property.
|
|
hideCodeBlock: true
|
|
- id: querying-with-count-option
|
|
name: Querying with count option
|
|
code: |
|
|
```swift
|
|
let count = try await supabase
|
|
.from("instruments")
|
|
.select("*", head: true, count: .exact)
|
|
.execute()
|
|
.count
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
instruments (id int8 primary key, name text);
|
|
|
|
insert into
|
|
instruments (id, name)
|
|
values
|
|
(1, 'dulcimer'),
|
|
(2, 'harp'),
|
|
(3, 'tuba');
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"count": 3,
|
|
"status": 200,
|
|
"statusText": "OK"
|
|
}
|
|
```
|
|
description: |
|
|
You can get the number of rows by using the
|
|
[count](/docs/reference/swift/v3/select#parameters) option.
|
|
hideCodeBlock: true
|
|
- id: querying-json-data
|
|
name: Querying JSON data
|
|
code: |
|
|
```swift
|
|
struct User: Decodable {
|
|
let id: Int
|
|
let name: String
|
|
let city: String
|
|
}
|
|
|
|
let users: [User] = try await supabase
|
|
.from("users")
|
|
.select(
|
|
"""
|
|
id, name,
|
|
address->city
|
|
"""
|
|
)
|
|
.execute()
|
|
.value
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
users (
|
|
id int8 primary key,
|
|
name text,
|
|
address jsonb
|
|
);
|
|
|
|
insert into
|
|
users (id, name, address)
|
|
values
|
|
(1, 'Frodo', '{"city":"Hobbiton"}');
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": [
|
|
{
|
|
"id": 1,
|
|
"name": "Frodo",
|
|
"city": "Hobbiton"
|
|
}
|
|
],
|
|
"status": 200,
|
|
"statusText": "OK"
|
|
}
|
|
```
|
|
description: |
|
|
You can select and filter data inside of
|
|
[JSON](/docs/guides/database/json) columns. Postgres offers some
|
|
[operators](/docs/guides/database/json#query-the-jsonb-data) for
|
|
querying JSON data.
|
|
hideCodeBlock: true
|
|
- id: querying-foreign-table-with-inner-join
|
|
name: Querying foreign table with inner join
|
|
code: |
|
|
```swift
|
|
struct Instrument: Decodable {
|
|
let name: String
|
|
}
|
|
|
|
struct OrchestralSection: Decodable {
|
|
let name: String
|
|
let instruments: [Instrument]
|
|
}
|
|
|
|
let orchestralSections: [OrchestralSection] = try await supabase
|
|
.from("orchestral_sections")
|
|
.select("name, instruments!inner(name)")
|
|
.eq("name", value: "strings")
|
|
.execute()
|
|
.value
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table orchestral_sections (
|
|
"id" "uuid" primary key default "extensions"."uuid_generate_v4"() not null,
|
|
"name" text
|
|
);
|
|
|
|
create table instruments (
|
|
"id" "uuid" primary key default "extensions"."uuid_generate_v4"() not null,
|
|
"name" text,
|
|
"section_id" "uuid" references public.orchestral_sections on delete cascade
|
|
);
|
|
|
|
with section as (
|
|
insert into orchestral_sections (name)
|
|
values ('strings') returning id
|
|
)
|
|
insert into instruments (name, section_id) values
|
|
('violin', (select id from section)),
|
|
('viola', (select id from section)),
|
|
('cello', (select id from section)),
|
|
('double bass', (select id from section));
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": [
|
|
{
|
|
"name": "strings",
|
|
"instruments": [
|
|
{
|
|
"name": "violin"
|
|
},
|
|
{
|
|
"name": "viola"
|
|
},
|
|
{
|
|
"name": "cello"
|
|
},
|
|
{
|
|
"name": "double bass"
|
|
}
|
|
]
|
|
}
|
|
],
|
|
"status": 200,
|
|
"statusText": "OK"
|
|
}
|
|
```
|
|
description: |
|
|
If you don't want to return the foreign table contents, you can leave the parenthesis empty.
|
|
Like `.select("name, instruments!inner()")`.
|
|
hideCodeBlock: true
|
|
- id: switching-schemas-per-query
|
|
name: Switching schemas per query
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.schema("myschema")
|
|
.from("mytable")
|
|
.select()
|
|
.execute()
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create schema myschema;
|
|
|
|
create table myschema.mytable (
|
|
id uuid primary key default gen_random_uuid(),
|
|
data text
|
|
);
|
|
|
|
insert into myschema.mytable (data) values ('mydata');
|
|
```
|
|
response: |
|
|
```json
|
|
[
|
|
{
|
|
"id": "4162e008-27b0-4c0f-82dc-ccaeee9a624d",
|
|
"data": "mydata"
|
|
}
|
|
]
|
|
```
|
|
description: |
|
|
In addition to setting the schema during initialization, you can also switch schemas on a per-query basis.
|
|
`schema(_:)` returns a `PostgrestClient` for that schema.
|
|
Make sure you've set up your [database privileges and API settings](/docs/guides/api/using-custom-schemas).
|
|
hideCodeBlock: true
|
|
|
|
- id: insert
|
|
title: 'Create data: insert()'
|
|
notes: |
|
|
- `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.
|
|
examples:
|
|
- id: create-a-record
|
|
name: Create a record
|
|
code: |
|
|
```swift
|
|
struct Instrument: Encodable {
|
|
let id: Int
|
|
let name: String
|
|
}
|
|
|
|
let instrument = Instrument(id: 1, name: "ukelele")
|
|
|
|
try await supabase
|
|
.from("instruments")
|
|
.insert(instrument)
|
|
.execute()
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
instruments (id int8 primary key, name text);
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"status": 201,
|
|
"statusText": "Created"
|
|
}
|
|
```
|
|
hideCodeBlock: true
|
|
isSpotlight: true
|
|
- id: create-a-record-and-return-it
|
|
name: Create a record and return it
|
|
code: |
|
|
```swift
|
|
struct Instrument: Codable {
|
|
let id: Int
|
|
let name: String
|
|
}
|
|
|
|
let instrument: Instrument = try await supabase
|
|
.from("instruments")
|
|
.insert(Instrument(id: 1, name: "banjo"))
|
|
.select()
|
|
// specify you want a single value returned, otherwise it returns a list.
|
|
.single()
|
|
.execute()
|
|
.value
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
instruments (id int8 primary key, name text);
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": [
|
|
{
|
|
"id": 1,
|
|
"name": "banjo"
|
|
}
|
|
],
|
|
"status": 201,
|
|
"statusText": "Created"
|
|
}
|
|
```
|
|
hideCodeBlock: true
|
|
- id: bulk-create
|
|
name: Bulk create
|
|
code: |
|
|
```swift
|
|
struct Instrument: Encodable {
|
|
let id: Int
|
|
let name: String
|
|
}
|
|
|
|
let instruments = [
|
|
Instrument(id: 1, name: "xylophone"),
|
|
Instrument(id: 2, name: "tuba"),
|
|
]
|
|
|
|
try await supabase
|
|
.from("instruments")
|
|
.insert(instruments)
|
|
.execute()
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
instruments (id int8 primary key, name text);
|
|
|
|
insert into
|
|
instruments (id, name)
|
|
values
|
|
(1, 'piano');
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"error": {
|
|
"code": "23505",
|
|
"details": "Key (id)=(1) already exists.",
|
|
"hint": null,
|
|
"message": "duplicate key value violates unique constraint \"instruments_pkey\""
|
|
},
|
|
"status": 409,
|
|
"statusText": "Conflict"
|
|
}
|
|
```
|
|
description: |
|
|
A bulk create operation is handled in a single transaction.
|
|
If any of the inserts fail, none of the rows are inserted. Here, a row
|
|
with `id` 1 already exists, so `tuba` is not inserted either.
|
|
hideCodeBlock: true
|
|
|
|
- id: update
|
|
title: 'Modify data: update()'
|
|
notes: |
|
|
- `update()` should always be combined with [Filters](/docs/reference/swift/v3/using-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.
|
|
examples:
|
|
- id: updating-your-data
|
|
name: Updating your data
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("instruments")
|
|
.update(["name": "piano"])
|
|
.eq("id", value: 1)
|
|
.execute()
|
|
```
|
|
notes: |
|
|
You don't always need an `Encodable` struct for the values to update.
|
|
This example passes a `[String: String]` directly, since it conforms
|
|
to `Encodable`.
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
instruments (id int8 primary key, name text);
|
|
|
|
insert into
|
|
instruments (id, name)
|
|
values
|
|
(1, 'harpsichord');
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"status": 204,
|
|
"statusText": "No Content"
|
|
}
|
|
```
|
|
hideCodeBlock: true
|
|
isSpotlight: true
|
|
- id: update-a-record-and-return-it
|
|
name: Update a record and return it
|
|
code: |
|
|
```swift
|
|
struct Instrument: Decodable {
|
|
let id: Int
|
|
let name: String
|
|
}
|
|
|
|
let instrument: Instrument = try await supabase
|
|
.from("instruments")
|
|
.update(["name": "piano"])
|
|
.eq("id", value: 1)
|
|
.select()
|
|
// If you know this query should return a single object, append a `single()` modifier to it.
|
|
.single()
|
|
.execute()
|
|
.value
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
instruments (id int8 primary key, name text);
|
|
|
|
insert into
|
|
instruments (id, name)
|
|
values
|
|
(1, 'harpsichord');
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": [
|
|
{
|
|
"id": 1,
|
|
"name": "piano"
|
|
}
|
|
],
|
|
"status": 200,
|
|
"statusText": "OK"
|
|
}
|
|
```
|
|
hideCodeBlock: true
|
|
- id: updating-json-data
|
|
name: Updating JSON data
|
|
code: |
|
|
```swift
|
|
struct User: Decodable {
|
|
let id: Int
|
|
let name: String
|
|
let address: Address
|
|
|
|
struct Address: Codable {
|
|
let street: String
|
|
let postcode: String
|
|
}
|
|
}
|
|
|
|
struct UpdateUser: Encodable {
|
|
let address: User.Address
|
|
}
|
|
|
|
let users: [User] = try await supabase
|
|
.from("users")
|
|
.update(
|
|
UpdateUser(
|
|
address: .init(
|
|
street: "Melrose Place",
|
|
postcode: "90210"
|
|
)
|
|
)
|
|
)
|
|
.eq("address->postcode", value: "90210")
|
|
.select()
|
|
.execute()
|
|
.value
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
users (
|
|
id int8 primary key,
|
|
name text,
|
|
address jsonb
|
|
);
|
|
|
|
insert into
|
|
users (id, name, address)
|
|
values
|
|
(1, 'Michael', '{ "postcode": "90210" }');
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": [
|
|
{
|
|
"id": 1,
|
|
"name": "Michael",
|
|
"address": {
|
|
"street": "Melrose Place",
|
|
"postcode": "90210"
|
|
}
|
|
}
|
|
],
|
|
"status": 200,
|
|
"statusText": "OK"
|
|
}
|
|
```
|
|
description: |
|
|
Postgres offers some
|
|
[operators](/docs/guides/database/json#query-the-jsonb-data) for
|
|
working with JSON data. Currently, it is only possible to update the entire JSON document.
|
|
hideCodeBlock: true
|
|
|
|
- id: upsert
|
|
title: 'Upsert data: upsert()'
|
|
notes: |
|
|
- 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.
|
|
examples:
|
|
- id: upsert-your-data
|
|
name: Upsert your data
|
|
code: |
|
|
```swift
|
|
struct Instrument: Encodable {
|
|
let id: Int
|
|
let name: String
|
|
}
|
|
try await supabase
|
|
.from("instruments")
|
|
.upsert(Instrument(id: 1, name: "piano"))
|
|
.execute()
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
instruments (id int8 primary key, name text);
|
|
|
|
insert into
|
|
instruments (id, name)
|
|
values
|
|
(1, 'harpsichord');
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": [
|
|
{
|
|
"id": 1,
|
|
"name": "piano"
|
|
}
|
|
],
|
|
"status": 201,
|
|
"statusText": "Created"
|
|
}
|
|
```
|
|
hideCodeBlock: true
|
|
isSpotlight: true
|
|
- id: bulk-upsert-your-data
|
|
name: Bulk Upsert your data
|
|
code: |
|
|
```swift
|
|
struct Instrument: Encodable {
|
|
let id: Int
|
|
let name: String
|
|
}
|
|
try await supabase
|
|
.from("instruments")
|
|
.upsert([
|
|
Instrument(id: 1, name: "piano"),
|
|
Instrument(id: 2, name: "harp"),
|
|
])
|
|
.execute()
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
instruments (id int8 primary key, name text);
|
|
|
|
insert into
|
|
instruments (id, name)
|
|
values
|
|
(1, 'harpsichord');
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": [
|
|
{
|
|
"id": 1,
|
|
"name": "piano"
|
|
},
|
|
{
|
|
"id": 2,
|
|
"name": "harp"
|
|
}
|
|
],
|
|
"status": 201,
|
|
"statusText": "Created"
|
|
}
|
|
```
|
|
hideCodeBlock: true
|
|
- id: upserting-into-tables-with-constraints
|
|
name: Upserting into tables with constraints
|
|
code: |
|
|
```swift
|
|
struct User: Encodable {
|
|
let handle: String
|
|
let displayName: String
|
|
|
|
enum CodingKeys: String, CodingKey {
|
|
case handle
|
|
case displayName = "display_name"
|
|
}
|
|
}
|
|
|
|
try await supabase
|
|
.from("users")
|
|
.upsert(
|
|
User(handle: "saoirse", displayName: "Saoirse"),
|
|
onConflict: "handle"
|
|
)
|
|
.select()
|
|
.execute()
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
users (
|
|
id int8 generated by default as identity primary key,
|
|
handle text not null unique,
|
|
display_name text
|
|
);
|
|
|
|
insert into
|
|
users (handle, display_name)
|
|
values
|
|
('saoirse', null);
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": [
|
|
{
|
|
"id": 1,
|
|
"handle": "saoirse",
|
|
"display_name": "Saoirse"
|
|
}
|
|
],
|
|
"status": 201,
|
|
"statusText": "Created"
|
|
}
|
|
```
|
|
description: |
|
|
By default, `upsert()` uses the primary key to find conflicts. This row
|
|
has no `id`, so without `onConflict`, `upsert()` inserts a new row. That
|
|
insert fails, because a row with `handle` `"saoirse"` already exists.
|
|
With `onConflict: "handle"`, `upsert()` uses the unique `handle` column
|
|
instead, so it updates the existing row.
|
|
hideCodeBlock: true
|
|
|
|
- id: delete
|
|
title: 'Delete data: delete()'
|
|
|
|
notes: |
|
|
- `delete()` should always be combined with [filters](/docs/reference/swift/v3/using-filters) to target the item(s) you wish to delete.
|
|
- If you use `delete()` with filters and you have
|
|
[RLS](/docs/learn/auth-deep-dive/auth-row-level-security) 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.
|
|
examples:
|
|
- id: delete-records
|
|
name: Delete records
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("instruments")
|
|
.delete()
|
|
.eq("id", value: 1)
|
|
.execute()
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
instruments (id int8 primary key, name text);
|
|
|
|
insert into
|
|
instruments (id, name)
|
|
values
|
|
(1, 'mandolin');
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"status": 204,
|
|
"statusText": "No Content"
|
|
}
|
|
```
|
|
hideCodeBlock: true
|
|
isSpotlight: true
|
|
- id: delete-a-record-and-return-it
|
|
name: Delete a record and return it
|
|
code: |
|
|
```swift
|
|
struct Instrument: Decodable {
|
|
let id: Int
|
|
let name: String
|
|
}
|
|
|
|
let deleted: [Instrument] = try await supabase
|
|
.from("instruments")
|
|
.delete()
|
|
.eq("id", value: 1)
|
|
.select()
|
|
.execute()
|
|
.value
|
|
```
|
|
description: |
|
|
Add `select()` after the filters to get the deleted rows back.
|
|
hideCodeBlock: true
|
|
|
|
- id: rpc
|
|
title: 'Postgres functions: rpc()'
|
|
description: |
|
|
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.
|
|
|
|
```sql
|
|
create or replace function hello_world() returns text as $$
|
|
select 'Hello world';
|
|
$$ language sql;
|
|
```
|
|
examples:
|
|
- id: call-a-postgres-function-without-arguments
|
|
name: Call a Postgres function without arguments
|
|
code: |
|
|
```swift
|
|
let value: String = try await supabase
|
|
.rpc("hello_world")
|
|
.execute()
|
|
.value
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create function hello_world() returns text as $$
|
|
select 'Hello world';
|
|
$$ language sql;
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": "Hello world",
|
|
"status": 200,
|
|
"statusText": "OK"
|
|
}
|
|
```
|
|
hideCodeBlock: true
|
|
isSpotlight: true
|
|
- id: call-a-postgres-function-with-arguments
|
|
name: Call a Postgres function with arguments
|
|
code: |
|
|
```swift
|
|
let response: String = try await supabase
|
|
.rpc("echo", params: ["say": "👋"])
|
|
.execute()
|
|
.value
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create function echo(say text) returns text as $$
|
|
select say;
|
|
$$ language sql;
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": "👋",
|
|
"status": 200,
|
|
"statusText": "OK"
|
|
}
|
|
```
|
|
hideCodeBlock: true
|
|
- id: bulk-processing
|
|
name: Bulk processing
|
|
code: |
|
|
```swift
|
|
let response: [Int] = try await supabase
|
|
.rpc("add_one_each", params: ["arr": [1, 2, 3]])
|
|
.execute()
|
|
.value
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create function add_one_each(arr int[]) returns int[] as $$
|
|
select array_agg(n + 1) from unnest(arr) as n;
|
|
$$ language sql;
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": [
|
|
2,
|
|
3,
|
|
4
|
|
],
|
|
"status": 200,
|
|
"statusText": "OK"
|
|
}
|
|
```
|
|
description: |
|
|
You can process large payloads by passing in an array as an argument.
|
|
hideCodeBlock: true
|
|
|
|
- id: call-a-postgres-function-with-filters
|
|
name: Call a Postgres function with filters
|
|
code: |
|
|
```swift
|
|
struct Instrument: Decodable {
|
|
let id: Int
|
|
let name: String
|
|
}
|
|
|
|
let instrument: Instrument = try await supabase
|
|
.rpc("list_stored_instruments")
|
|
.eq("id", value: 1)
|
|
.single()
|
|
.execute()
|
|
.value
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
instruments (id int8 primary key, name text);
|
|
|
|
insert into
|
|
instruments (id, name)
|
|
values
|
|
(1, 'klaxon'),
|
|
(2, 'marimba');
|
|
|
|
create function list_stored_instruments() returns setof instruments as $$
|
|
select * from instruments;
|
|
$$ language sql;
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": {
|
|
"id": 1,
|
|
"name": "klaxon"
|
|
},
|
|
"status": 200,
|
|
"statusText": "OK"
|
|
}
|
|
```
|
|
description: |
|
|
Postgres functions that return tables can also be combined with
|
|
[Filters](/docs/reference/swift/v3/using-filters) and
|
|
[Modifiers](/docs/reference/swift/v3/using-modifiers).
|
|
hideCodeBlock: true
|
|
|
|
- id: using-filters
|
|
title: Using Filters
|
|
description: |
|
|
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](https://postgrest.org/en/stable/references/api/tables_views.html#operators).
|
|
examples:
|
|
- id: applying-filters
|
|
name: Applying Filters
|
|
description: |
|
|
Filters must be applied after any of `select()`, `update()`,
|
|
`delete()`, and `rpc()` and before
|
|
[modifiers](/docs/reference/swift/v3/using-modifiers).
|
|
code: |
|
|
```swift
|
|
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")
|
|
```
|
|
- id: chaining-filters
|
|
name: Chaining
|
|
description: |
|
|
Filters can be chained together to produce advanced queries. For example,
|
|
to query cities with population between 1,000 and 10,000:
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("cities")
|
|
.select("name, country_id")
|
|
.gte("population", value: 1000)
|
|
.lt("population", value: 10000)
|
|
.execute()
|
|
```
|
|
- id: conditional-chaining
|
|
name: Conditional Chaining
|
|
description: |
|
|
Filters can be built up one step at a time and then executed. Each
|
|
filter returns a new query, so assign the result back to the variable.
|
|
code: |
|
|
```swift
|
|
let filterByName: String? = nil
|
|
let filterPopLow: Int? = 1000
|
|
let filterPopHigh: Int? = 10000
|
|
|
|
var query = supabase
|
|
.from("cities")
|
|
.select("name, country_id")
|
|
|
|
if let filterByName {
|
|
query = query.eq("name", value: filterByName)
|
|
}
|
|
if let filterPopLow {
|
|
query = query.gte("population", value: filterPopLow)
|
|
}
|
|
if let filterPopHigh {
|
|
query = query.lt("population", value: filterPopHigh)
|
|
}
|
|
|
|
struct City: Decodable {
|
|
let name: String
|
|
let countryId: Int
|
|
|
|
enum CodingKeys: String, CodingKey {
|
|
case name
|
|
case countryId = "country_id"
|
|
}
|
|
}
|
|
let cities: [City] = try await query.execute().value
|
|
```
|
|
- id: filter-by-value-within-json-column
|
|
name: Filter by values within a JSON column
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("users")
|
|
.select()
|
|
.eq("address->postcode", value: 90210)
|
|
.execute()
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
users (
|
|
id int8 primary key,
|
|
name text,
|
|
address jsonb
|
|
);
|
|
|
|
insert into
|
|
users (id, name, address)
|
|
values
|
|
(1, 'Michael', '{ "postcode": 90210 }'),
|
|
(2, 'Jane', null);
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": [
|
|
{
|
|
"id": 1,
|
|
"name": "Michael",
|
|
"address": {
|
|
"postcode": 90210
|
|
}
|
|
}
|
|
],
|
|
"status": 200,
|
|
"statusText": "OK"
|
|
}
|
|
```
|
|
- id: filter-foreign-tables
|
|
name: Filter Foreign Tables
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("orchestral_sections")
|
|
.select(
|
|
"""
|
|
name,
|
|
instruments!inner (
|
|
name
|
|
)
|
|
"""
|
|
)
|
|
.eq("instruments.name", value: "flute")
|
|
.execute()
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
orchestral_sections (id int8 primary key, name text);
|
|
create table
|
|
instruments (
|
|
id int8 primary key,
|
|
section_id int8 not null references orchestral_sections,
|
|
name text
|
|
);
|
|
|
|
insert into
|
|
orchestral_sections (id, name)
|
|
values
|
|
(1, 'strings'),
|
|
(2, 'woodwinds');
|
|
insert into
|
|
instruments (id, section_id, name)
|
|
values
|
|
(1, 2, 'flute'),
|
|
(2, 1, 'violin');
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": [
|
|
{
|
|
"name": "woodwinds",
|
|
"instruments": [
|
|
{
|
|
"name": "flute"
|
|
}
|
|
]
|
|
}
|
|
],
|
|
"status": 200,
|
|
"statusText": "OK"
|
|
}
|
|
```
|
|
description: |
|
|
You can filter on foreign tables in your `select()` query using dot
|
|
notation.
|
|
- id: or
|
|
title: or()
|
|
notes: |
|
|
or() expects you to use the raw PostgREST syntax for the filter names and values.
|
|
|
|
```swift
|
|
.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()`
|
|
```
|
|
examples:
|
|
- id: with-select
|
|
name: With `select()`
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("instruments")
|
|
.select("name")
|
|
.or("id.eq.2,name.eq.cello")
|
|
.execute()
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
instruments (id int8 primary key, name text);
|
|
|
|
insert into
|
|
instruments (id, name)
|
|
values
|
|
(1, 'violin'),
|
|
(2, 'viola'),
|
|
(3, 'cello');
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": [
|
|
{
|
|
"name": "viola"
|
|
},
|
|
{
|
|
"name": "cello"
|
|
}
|
|
],
|
|
"status": 200,
|
|
"statusText": "OK"
|
|
}
|
|
```
|
|
hideCodeBlock: true
|
|
isSpotlight: true
|
|
- id: use-or-with-and
|
|
name: Use `or` with `and`
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("instruments")
|
|
.select("name")
|
|
.or("id.gt.3,and(id.eq.1,name.eq.violin)")
|
|
.execute()
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
instruments (id int8 primary key, name text);
|
|
|
|
insert into
|
|
instruments (id, name)
|
|
values
|
|
(1, 'violin'),
|
|
(2, 'viola'),
|
|
(3, 'cello');
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": [
|
|
{
|
|
"name": "violin"
|
|
}
|
|
],
|
|
"status": 200,
|
|
"statusText": "OK"
|
|
}
|
|
```
|
|
hideCodeBlock: true
|
|
|
|
- id: not
|
|
title: not()
|
|
description: |
|
|
Finds all rows that don't satisfy the filter.
|
|
notes: |
|
|
- `.not()` expects you to use the raw [PostgREST syntax](https://postgrest.org/en/stable/api.html#horizontal-filtering-rows) for the filter names and values.
|
|
|
|
```swift
|
|
.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.
|
|
```
|
|
examples:
|
|
- id: with-select
|
|
name: With `select()`
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("instruments")
|
|
.select()
|
|
.not("name", operator: .is, value: "null")
|
|
.execute()
|
|
```
|
|
|
|
- id: match
|
|
title: match()
|
|
examples:
|
|
- id: with-select
|
|
name: With `select()`
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("instruments")
|
|
.select("name")
|
|
.match(["id": 2, "name": "viola"])
|
|
.execute()
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
instruments (id int8 primary key, name text);
|
|
|
|
insert into
|
|
instruments (id, name)
|
|
values
|
|
(1, 'violin'),
|
|
(2, 'viola'),
|
|
(3, 'cello');
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": [
|
|
{
|
|
"name": "viola"
|
|
}
|
|
],
|
|
"status": 200,
|
|
"statusText": "OK"
|
|
}
|
|
```
|
|
hideCodeBlock: true
|
|
isSpotlight: true
|
|
|
|
- id: filter
|
|
title: filter()
|
|
notes: |
|
|
filter() expects you to use the raw PostgREST syntax for the filter values.
|
|
|
|
```swift
|
|
.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
|
|
```
|
|
examples:
|
|
- id: with-select
|
|
name: With `select()`
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("instruments")
|
|
.select()
|
|
.filter("name", operator: "in", value: #"("cello","guzheng")"#)
|
|
.execute()
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
instruments (id int8 primary key, name text);
|
|
|
|
insert into
|
|
instruments (id, name)
|
|
values
|
|
(1, 'violin'),
|
|
(2, 'viola'),
|
|
(3, 'cello');
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": [
|
|
{
|
|
"id": 3,
|
|
"name": "cello"
|
|
}
|
|
],
|
|
"status": 200,
|
|
"statusText": "OK"
|
|
}
|
|
```
|
|
hideCodeBlock: true
|
|
isSpotlight: true
|
|
- id: on-a-foreign-table
|
|
name: On a foreign table
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("orchestral_sections")
|
|
.select(
|
|
"""
|
|
name,
|
|
instruments!inner (
|
|
name
|
|
)
|
|
"""
|
|
)
|
|
.filter("instruments.name", operator: "eq", value: "flute")
|
|
.execute()
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
orchestral_sections (id int8 primary key, name text);
|
|
create table
|
|
instruments (
|
|
id int8 primary key,
|
|
section_id int8 not null references orchestral_sections,
|
|
name text
|
|
);
|
|
|
|
insert into
|
|
orchestral_sections (id, name)
|
|
values
|
|
(1, 'strings'),
|
|
(2, 'woodwinds');
|
|
insert into
|
|
instruments (id, section_id, name)
|
|
values
|
|
(1, 2, 'flute'),
|
|
(2, 1, 'violin');
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": [
|
|
{
|
|
"name": "woodwinds",
|
|
"instruments": [
|
|
{
|
|
"name": "flute"
|
|
}
|
|
]
|
|
}
|
|
],
|
|
"status": 200,
|
|
"statusText": "OK"
|
|
}
|
|
```
|
|
hideCodeBlock: true
|
|
|
|
- id: eq
|
|
title: eq()
|
|
description: |
|
|
Match only rows where `column` is equal to `value`.
|
|
examples:
|
|
- id: with-select
|
|
name: With `select()`
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("cities")
|
|
.select("name, country_id")
|
|
.eq("name", value: "The shire")
|
|
.execute()
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": [
|
|
{
|
|
"name": "The shire",
|
|
"country_id": 554
|
|
}
|
|
],
|
|
"status": 200,
|
|
"statusText": "OK"
|
|
}
|
|
```
|
|
|
|
- id: neq
|
|
title: neq()
|
|
description: |
|
|
Match only rows where `column` is not equal to `value`.
|
|
examples:
|
|
- id: with-select
|
|
name: With `select()`
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("cities")
|
|
.select("name, country_id")
|
|
.neq("name", value: "Paris")
|
|
.execute()
|
|
```
|
|
|
|
- id: gt
|
|
title: gt()
|
|
description: |
|
|
Match only rows where `column` is greater than `value`.
|
|
examples:
|
|
- id: with-select
|
|
name: With `select()`
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("cities")
|
|
.select("name, country_id")
|
|
.gt("country_id", value: 250)
|
|
.execute()
|
|
```
|
|
|
|
- id: gte
|
|
title: gte()
|
|
description: |
|
|
Match only rows where `column` is greater than or equal to `value`.
|
|
examples:
|
|
- id: with-select
|
|
name: With `select()`
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("cities")
|
|
.select("name, country_id")
|
|
.gte("country_id", value: 250)
|
|
.execute()
|
|
```
|
|
|
|
- id: lt
|
|
title: lt()
|
|
description: |
|
|
Match only rows where `column` is less than `value`.
|
|
examples:
|
|
- id: with-select
|
|
name: With `select()`
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("cities")
|
|
.select("name, country_id")
|
|
.lt("country_id", value: 250)
|
|
.execute()
|
|
```
|
|
|
|
- id: lte
|
|
title: lte()
|
|
description: |
|
|
Match only rows where `column` is less than or equal to `value`.
|
|
examples:
|
|
- id: with-select
|
|
name: With `select()`
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("cities")
|
|
.select("name, country_id")
|
|
.lte("country_id", value: 250)
|
|
.execute()
|
|
```
|
|
|
|
- id: like
|
|
title: like()
|
|
description: |
|
|
Match only rows where `column` matches `pattern` case-sensitively.
|
|
examples:
|
|
- id: with-select
|
|
name: With `select()`
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("cities")
|
|
.select("name, country_id")
|
|
.like("name", pattern: "%la%")
|
|
.execute()
|
|
```
|
|
|
|
- id: ilike
|
|
title: ilike()
|
|
description: |
|
|
Match only rows where `column` matches `pattern` case-insensitively.
|
|
examples:
|
|
- id: with-select
|
|
name: With `select()`
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("cities")
|
|
.select("name, country_id")
|
|
.ilike("name", pattern: "%la%")
|
|
.execute()
|
|
```
|
|
|
|
- id: is
|
|
title: is()
|
|
description: |
|
|
Match only rows where `column` IS `value`. `value` is `nil`, `true`, or `false`.
|
|
|
|
Use `is()` to match `NULL`. `eq()` doesn't take `nil`.
|
|
examples:
|
|
- id: with-select
|
|
name: With `select()`
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("cities")
|
|
.select("name, country_id")
|
|
.is("name", value: nil)
|
|
.execute()
|
|
```
|
|
|
|
- id: in
|
|
title: in()
|
|
description: |
|
|
Match only rows where `column` is included in the `values` array.
|
|
examples:
|
|
- id: with-select
|
|
name: With `select()`
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("cities")
|
|
.select("name, country_id")
|
|
.in("name", values: ["Rio de Janeiro", "San Francisco"])
|
|
.execute()
|
|
```
|
|
|
|
- id: notin
|
|
title: notIn()
|
|
description: |
|
|
Match only rows where `column` is not included in the `values` array. The negation of `in()`.
|
|
examples:
|
|
- id: with-select
|
|
name: With `select()`
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("cities")
|
|
.select("name, country_id")
|
|
.notIn("name", values: ["Rio de Janeiro", "San Francisco"])
|
|
.execute()
|
|
```
|
|
|
|
- id: contains
|
|
title: contains()
|
|
description: |
|
|
Match only rows where `column` contains every element appearing in `value`.
|
|
examples:
|
|
- id: with-select
|
|
name: With `select()`
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("cities")
|
|
.select("name, main_exports")
|
|
.contains("main_exports", value: ["oil"])
|
|
.execute()
|
|
```
|
|
|
|
- id: contained-by
|
|
title: containedBy()
|
|
description: |
|
|
Match only rows where every element in `column` appears in `value`.
|
|
examples:
|
|
- id: with-select
|
|
name: With `select()`
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("cities")
|
|
.select("name, main_exports")
|
|
.containedBy("main_exports", value: ["cars", "food", "machine"])
|
|
.execute()
|
|
```
|
|
|
|
- id: overlaps
|
|
title: overlaps()
|
|
description: |
|
|
Match only rows where `column` and `value` have an element in common.
|
|
examples:
|
|
- id: with-select
|
|
name: With `select()`
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("cities")
|
|
.select("name, main_exports")
|
|
.overlaps("main_exports", value: ["exports", "tourism"])
|
|
.execute()
|
|
```
|
|
|
|
- id: range-lt
|
|
title: rangeLt()
|
|
description: |
|
|
Match only rows where every element in `column` is less than any element in `range`.
|
|
examples:
|
|
- id: with-select
|
|
name: With `select()`
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("reservations")
|
|
.select()
|
|
.rangeLt("during", range: "[2000-01-02 08:30, 2000-01-02 09:30)")
|
|
.execute()
|
|
```
|
|
|
|
- id: range-gt
|
|
title: rangeGt()
|
|
description: |
|
|
Match only rows where every element in `column` is greater than any element in `range`.
|
|
examples:
|
|
- id: with-select
|
|
name: With `select()`
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("reservations")
|
|
.select()
|
|
.rangeGt("during", range: "[2000-01-02 08:30, 2000-01-02 09:30)")
|
|
.execute()
|
|
```
|
|
|
|
- id: range-gte
|
|
title: rangeGte()
|
|
description: |
|
|
Match only rows where every element in `column` is either contained in `range` or greater than any element in `range`.
|
|
examples:
|
|
- id: with-select
|
|
name: With `select()`
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("reservations")
|
|
.select()
|
|
.rangeGte("during", range: "[2000-01-02 08:30, 2000-01-02 09:30)")
|
|
.execute()
|
|
```
|
|
|
|
- id: range-lte
|
|
title: rangeLte()
|
|
description: |
|
|
Match only rows where every element in `column` is either contained in `range` or less than any element in `range`.
|
|
examples:
|
|
- id: with-select
|
|
name: With `select()`
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("reservations")
|
|
.select()
|
|
.rangeLte("during", range: "[2000-01-02 08:30, 2000-01-02 09:30)")
|
|
.execute()
|
|
```
|
|
|
|
- id: range-adjacent
|
|
title: rangeAdjacent()
|
|
description: |
|
|
Match only rows where `column` is adjacent to `range`.
|
|
examples:
|
|
- id: with-select
|
|
name: With `select()`
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("reservations")
|
|
.select()
|
|
.rangeAdjacent("during", range: "[2000-01-02 08:30, 2000-01-02 09:30)")
|
|
.execute()
|
|
```
|
|
|
|
- id: text-search
|
|
title: textSearch()
|
|
description: |
|
|
Match only rows where `column` matches the query string in `query`.
|
|
notes: |
|
|
- `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`.
|
|
examples:
|
|
- id: with-select
|
|
name: With `select()`
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("quotes")
|
|
.select("catchphrase")
|
|
.textSearch("catchphrase", query: "'fat' & 'cat'", config: "english")
|
|
.execute()
|
|
```
|
|
- id: websearch
|
|
name: Websearch
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("quotes")
|
|
.select("catchphrase")
|
|
.textSearch("catchphrase", query: "'fat' or 'cat'", config: "english", type: .websearch)
|
|
.execute()
|
|
```
|
|
|
|
- id: using-modifiers
|
|
title: Using Modifiers
|
|
description: |
|
|
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).
|
|
|
|
- id: db-modifiers-select
|
|
title: select()
|
|
description: |
|
|
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.
|
|
examples:
|
|
- id: with-upsert
|
|
name: With `upsert()`
|
|
code: |
|
|
```swift
|
|
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
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
instruments (id int8 primary key, name text);
|
|
|
|
insert into
|
|
instruments (id, name)
|
|
values
|
|
(1, 'harpsichord');
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": [
|
|
{
|
|
"id": 1,
|
|
"name": "piano"
|
|
}
|
|
],
|
|
"status": 201,
|
|
"statusText": "Created"
|
|
}
|
|
```
|
|
hideCodeBlock: true
|
|
isSpotlight: true
|
|
- id: order
|
|
title: order()
|
|
description: |
|
|
Order the query result by column.
|
|
notes: |
|
|
- `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.
|
|
examples:
|
|
- id: with-select
|
|
name: With `select()`
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("instruments")
|
|
.select("id, name")
|
|
.order("id", ascending: false)
|
|
.execute()
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
instruments (id int8 primary key, name text);
|
|
|
|
insert into
|
|
instruments (id, name)
|
|
values
|
|
(1, 'violin'),
|
|
(2, 'viola'),
|
|
(3, 'cello');
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": [
|
|
{
|
|
"id": 3,
|
|
"name": "cello"
|
|
},
|
|
{
|
|
"id": 2,
|
|
"name": "viola"
|
|
},
|
|
{
|
|
"id": 1,
|
|
"name": "viola"
|
|
}
|
|
],
|
|
"status": 200,
|
|
"statusText": "OK"
|
|
}
|
|
```
|
|
hideCodeBlock: true
|
|
isSpotlight: true
|
|
- id: on-a-foreign-table
|
|
name: On a foreign table
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("orchestral_sections")
|
|
.select(
|
|
"""
|
|
name,
|
|
instruments (
|
|
name
|
|
)
|
|
"""
|
|
)
|
|
.order("name", ascending: false, referencedTable: "instruments")
|
|
.execute()
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
orchestral_sections (id int8 primary key, name text);
|
|
create table
|
|
instruments (
|
|
id int8 primary key,
|
|
section_id int8 not null references orchestral_sections,
|
|
name text
|
|
);
|
|
|
|
insert into
|
|
orchestral_sections (id, name)
|
|
values
|
|
(1, 'strings'),
|
|
(2, 'woodwinds');
|
|
insert into
|
|
instruments (id, section_id, name)
|
|
values
|
|
(1, 1, 'harp'),
|
|
(2, 1, 'violin');
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": [
|
|
{
|
|
"name": "strings",
|
|
"instruments": [
|
|
{
|
|
"name": "violin"
|
|
},
|
|
{
|
|
"name": "harp"
|
|
}
|
|
]
|
|
},
|
|
{
|
|
"name": "woodwinds",
|
|
"instruments": []
|
|
}
|
|
],
|
|
"status": 200,
|
|
"statusText": "OK"
|
|
}
|
|
```
|
|
description: |
|
|
Ordering on foreign tables doesn't affect the ordering of
|
|
the parent table.
|
|
hideCodeBlock: true
|
|
- id: order-parent-table-by-a-referenced-table
|
|
name: Order parent table by a referenced table
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("instruments")
|
|
.select(
|
|
"""
|
|
name,
|
|
section:orchestral_sections (
|
|
name
|
|
)
|
|
"""
|
|
)
|
|
.order("section(name)", ascending: true)
|
|
.execute()
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
orchestral_sections (id int8 primary key, name text);
|
|
create table
|
|
instruments (
|
|
id int8 primary key,
|
|
section_id int8 not null references orchestral_sections,
|
|
name text
|
|
);
|
|
|
|
insert into
|
|
orchestral_sections (id, name)
|
|
values
|
|
(1, 'strings'),
|
|
(2, 'woodwinds');
|
|
insert into
|
|
instruments (id, section_id, name)
|
|
values
|
|
(1, 1, 'violin'),
|
|
(2, 2, 'flute');
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": [
|
|
{
|
|
"name": "violin",
|
|
"section": { "name": "strings" }
|
|
},
|
|
{
|
|
"name": "flute",
|
|
"section": { "name": "woodwinds" }
|
|
}
|
|
],
|
|
"status": 200,
|
|
"statusText": "OK"
|
|
}
|
|
```
|
|
description: |
|
|
Ordering with `referenced_table(col)` affects the ordering of the
|
|
parent table.
|
|
hideCodeBlock: true
|
|
|
|
- id: limit
|
|
title: limit()
|
|
description: |
|
|
Limit the query result by count.
|
|
examples:
|
|
- id: with-select
|
|
name: With `select()`
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("instruments")
|
|
.select("id, name")
|
|
.limit(1)
|
|
.execute()
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
instruments (id int8 primary key, name text);
|
|
|
|
insert into
|
|
instruments (id, name)
|
|
values
|
|
(1, 'violin'),
|
|
(2, 'viola'),
|
|
(3, 'cello');
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": [
|
|
{
|
|
"name": "violin"
|
|
}
|
|
],
|
|
"status": 200,
|
|
"statusText": "OK"
|
|
}
|
|
```
|
|
hideCodeBlock: true
|
|
isSpotlight: true
|
|
- id: on-a-foreign-table
|
|
name: On a foreign table
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("orchestral_sections")
|
|
.select(
|
|
"""
|
|
name,
|
|
instruments (
|
|
name
|
|
)
|
|
"""
|
|
)
|
|
.limit(1, referencedTable: "instruments")
|
|
.execute()
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
orchestral_sections (id int8 primary key, name text);
|
|
create table
|
|
instruments (
|
|
id int8 primary key,
|
|
section_id int8 not null references orchestral_sections,
|
|
name text
|
|
);
|
|
|
|
insert into
|
|
orchestral_sections (id, name)
|
|
values
|
|
(1, 'woodwinds');
|
|
insert into
|
|
instruments (id, section_id, name)
|
|
values
|
|
(1, 1, 'flute'),
|
|
(2, 1, 'oboe');
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": [
|
|
{
|
|
"name": "woodwinds",
|
|
"instruments": [
|
|
{
|
|
"name": "flute"
|
|
}
|
|
]
|
|
}
|
|
],
|
|
"status": 200,
|
|
"statusText": "OK"
|
|
}
|
|
```
|
|
hideCodeBlock: true
|
|
- id: range
|
|
title: range()
|
|
description: |
|
|
Limit the query result by from and to inclusively.
|
|
examples:
|
|
- id: with-select
|
|
name: With `select()`
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("instruments")
|
|
.select("name")
|
|
.range(from: 0, to: 1)
|
|
.execute()
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
instruments (id int8 primary key, name text);
|
|
|
|
insert into
|
|
instruments (id, name)
|
|
values
|
|
(1, 'violin'),
|
|
(2, 'viola'),
|
|
(3, 'cello');
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": [
|
|
{
|
|
"name": "violin"
|
|
},
|
|
{
|
|
"name": "viola"
|
|
}
|
|
],
|
|
"status": 200,
|
|
"statusText": "OK"
|
|
}
|
|
```
|
|
hideCodeBlock: true
|
|
isSpotlight: true
|
|
|
|
- id: max-affected
|
|
title: maxAffected()
|
|
description: |
|
|
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.
|
|
notes: |
|
|
- 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.
|
|
examples:
|
|
- id: with-update
|
|
name: With `update()`
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("users")
|
|
.update(["status": "active"])
|
|
.eq("id", value: 1)
|
|
.maxAffected(1)
|
|
.execute()
|
|
```
|
|
description: |
|
|
Ensure that only one row is updated. If the query would update more than one row, an error is returned.
|
|
isSpotlight: true
|
|
- id: with-delete
|
|
name: With `delete()`
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("users")
|
|
.delete()
|
|
.in("id", values: [1, 2, 3])
|
|
.maxAffected(3)
|
|
.execute()
|
|
```
|
|
description: |
|
|
Ensure that only three rows are deleted. If the query would delete more than three rows, an error is returned.
|
|
- id: with-rpc
|
|
name: With `rpc()`
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.rpc("delete_inactive_users")
|
|
.maxAffected(10)
|
|
.execute()
|
|
```
|
|
description: |
|
|
Ensure that the RPC call affects at most 10 rows. Useful for limiting the impact of functions.
|
|
|
|
PostgREST counts the rows that the function returns, not the rows that it writes. For this check to protect your data, the function must return one row for each row it changes:
|
|
|
|
```sql
|
|
create function delete_inactive_users() returns setof users as $$
|
|
delete from users
|
|
where last_seen_at < now() - interval '1 year'
|
|
returning *;
|
|
$$ language sql;
|
|
```
|
|
|
|
- id: dry-run
|
|
title: dryRun()
|
|
description: |
|
|
Executes the mutation but rolls back the transaction instead of committing it, so its changes in the transaction are not persisted.
|
|
notes: |
|
|
- 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.
|
|
examples:
|
|
- id: with-update
|
|
name: With `update()`
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("todos")
|
|
.update(["done": true])
|
|
.eq("id", value: 1)
|
|
.select()
|
|
.dryRun()
|
|
.execute()
|
|
// Row is not actually updated in the database.
|
|
```
|
|
|
|
- id: single
|
|
title: single()
|
|
description: |
|
|
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`.
|
|
examples:
|
|
- id: with-select
|
|
name: With `select()`
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("instruments")
|
|
.select("name")
|
|
.limit(1)
|
|
.single()
|
|
.execute()
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
instruments (id int8 primary key, name text);
|
|
|
|
insert into
|
|
instruments (id, name)
|
|
values
|
|
(1, 'violin'),
|
|
(2, 'viola'),
|
|
(3, 'cello');
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": {
|
|
"name": "violin"
|
|
},
|
|
"status": 200,
|
|
"statusText": "OK"
|
|
}
|
|
```
|
|
hideCodeBlock: true
|
|
isSpotlight: true
|
|
|
|
- id: maybe-single
|
|
title: maybeSingle()
|
|
description: |
|
|
Return at most one row. When no row matches, `value` is `nil`. Decode into an optional type to get the `nil`.
|
|
notes: |
|
|
- 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.
|
|
examples:
|
|
- id: with-select
|
|
name: With `select()`
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let todo: Todo? = try await supabase
|
|
.from("todos")
|
|
.select()
|
|
.eq("id", value: 42)
|
|
.maybeSingle()
|
|
.execute()
|
|
.value
|
|
```
|
|
|
|
- id: csv
|
|
title: csv()
|
|
examples:
|
|
- id: return-data-as-csv
|
|
name: Return data as CSV
|
|
code: |
|
|
```swift
|
|
let csv = try await supabase
|
|
.from("instruments")
|
|
.select()
|
|
.csv()
|
|
.execute()
|
|
.string()
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
instruments (id int8 primary key, name text);
|
|
|
|
insert into
|
|
instruments (id, name)
|
|
values
|
|
(1, 'violin'),
|
|
(2, 'viola'),
|
|
(3, 'cello');
|
|
```
|
|
response: |
|
|
```json
|
|
{
|
|
"data": "id,name\n1,violin\n2,viola\n3,cello",
|
|
"status": 200,
|
|
"statusText": "OK"
|
|
}
|
|
```
|
|
description: |
|
|
By default, the data is returned in JSON format, but can also be returned as Comma Separated Values.
|
|
Read the CSV text with `string()` on the response.
|
|
hideCodeBlock: true
|
|
isSpotlight: true
|
|
- id: strip-nulls
|
|
title: stripNulls()
|
|
description: |
|
|
Strip null values from the response.
|
|
notes: |
|
|
- 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.
|
|
examples:
|
|
- id: strip-nulls
|
|
name: Strip null values
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
struct Character: Decodable {
|
|
let id: Int
|
|
let name: String
|
|
let nickname: String?
|
|
}
|
|
|
|
let characters: [Character] = try await supabase
|
|
.from("characters")
|
|
.select()
|
|
.stripNulls()
|
|
.execute()
|
|
.value
|
|
```
|
|
- id: explain
|
|
title: Using Explain
|
|
description: |
|
|
For debugging slow queries, you can get the [Postgres `EXPLAIN` execution plan](https://www.postgresql.org/docs/current/sql-explain.html) 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](/docs/guides/database/debugging-performance) to enable the functionality on your project.
|
|
notes: |
|
|
- The `format` parameter takes an `ExplainFormat` value: `.text` (the default, human-readable) or `.json` (machine-readable).
|
|
- Read the plan with `string()` on the response.
|
|
examples:
|
|
- id: get-execution-plan
|
|
name: Get the execution plan
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("instruments")
|
|
.select()
|
|
.explain()
|
|
.execute()
|
|
.string()
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
instruments (id int8 primary key, name text);
|
|
|
|
insert into
|
|
instruments (id, name)
|
|
values
|
|
(1, 'violin'),
|
|
(2, 'viola'),
|
|
(3, 'cello');
|
|
```
|
|
response: |
|
|
```
|
|
Aggregate (cost=33.34..33.36 rows=1 width=112)
|
|
-> Limit (cost=0.00..18.33 rows=1000 width=40)
|
|
-> Seq Scan on instruments (cost=0.00..22.00 rows=1200 width=40)
|
|
```
|
|
description: |
|
|
By default, the data is returned in TEXT format, but can also be returned as JSON by using the `format` parameter.
|
|
hideCodeBlock: true
|
|
isSpotlight: true
|
|
|
|
- id: get-execution-plan-with-analyze-and-verbose
|
|
name: Get the execution plan with analyze and verbose
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("instruments")
|
|
.select()
|
|
.explain(
|
|
analyze: true,
|
|
verbose: true
|
|
)
|
|
.execute()
|
|
.string()
|
|
```
|
|
data:
|
|
sql: |
|
|
```sql
|
|
create table
|
|
instruments (id int8 primary key, name text);
|
|
|
|
insert into
|
|
instruments (id, name)
|
|
values
|
|
(1, 'violin'),
|
|
(2, 'viola'),
|
|
(3, 'cello');
|
|
```
|
|
response: |
|
|
```
|
|
Aggregate (cost=33.34..33.36 rows=1 width=112) (actual time=0.041..0.041 rows=1 loops=1)
|
|
Output: NULL::bigint, count(ROW(instruments.id, instruments.name)), COALESCE(json_agg(ROW(instruments.id, instruments.name)), '[]'::json), NULLIF(current_setting('response.headers'::text, true), ''::text), NULLIF(current_setting('response.status'::text, true), ''::text)
|
|
-> Limit (cost=0.00..18.33 rows=1000 width=40) (actual time=0.005..0.006 rows=3 loops=1)
|
|
Output: instruments.id, instruments.name
|
|
-> Seq Scan on public.instruments (cost=0.00..22.00 rows=1200 width=40) (actual time=0.004..0.005 rows=3 loops=1)
|
|
Output: instruments.id, instruments.name
|
|
Query Identifier: -4730654291623321173
|
|
Planning Time: 0.407 ms
|
|
Execution Time: 0.119 ms
|
|
```
|
|
description: |
|
|
By default, the data is returned in TEXT format, but can also be returned as JSON by using the `format` parameter.
|
|
hideCodeBlock: true
|
|
isSpotlight: false
|
|
|
|
- id: get-execution-plan-json-format
|
|
name: Get the execution plan as JSON
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.from("instruments")
|
|
.select()
|
|
.explain(format: .json)
|
|
.execute()
|
|
.string()
|
|
```
|
|
description: |
|
|
Use `format: .json` to get a machine-readable JSON execution plan. The `ExplainFormat` type accepts `.text` (default) or `.json`.
|
|
isSpotlight: false
|
|
- id: invoke
|
|
title: invoke()
|
|
description: |
|
|
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.
|
|
notes: |
|
|
- 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](/docs/guides/functions/limits), after which a 504 Gateway Timeout is returned regardless of the value passed.
|
|
examples:
|
|
- id: invocation-with-decodable
|
|
name: Invocation with `Decodable` response
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
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
|
|
)
|
|
```
|
|
- id: invocation-with-custom-response
|
|
name: Invocation with custom response
|
|
description: |
|
|
Without a `Decodable` type, `invoke` returns a `FunctionResponse`. Read the status, headers, and raw body from it.
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let response = try await supabase.functions.invoke(
|
|
"hello",
|
|
body: .json(["foo": "bar"])
|
|
)
|
|
|
|
print(response.status.code) // Int
|
|
print(response.text ?? "") // The body as a UTF-8 string
|
|
print(response.body) // Data
|
|
```
|
|
- id: error-handling
|
|
name: Error handling
|
|
description: |
|
|
`invoke` throws a `FunctionsError`. Check its `kind`:
|
|
- `.server` when the function returns a non-2xx status. The status and body are in `response`.
|
|
- `.relay` when the Supabase Relay has an error processing your function.
|
|
- `.transport` when the request fails on the network. The original `URLError` is in `underlyingError`.
|
|
- `.decoding` when the response body does not decode as the type you asked for.
|
|
|
|
`Kind` is an open set, so keep a `default:` branch. A cancelled call throws `CancellationError`.
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
do {
|
|
let response = try await supabase.functions.invoke(
|
|
"hello",
|
|
body: .json(["foo": "bar"])
|
|
)
|
|
} catch let error as FunctionsError {
|
|
switch error.kind {
|
|
case .server:
|
|
let code = error.response?.status.code ?? 0
|
|
let body = String(decoding: error.response?.body ?? Data(), as: UTF8.self)
|
|
print("Function returned code \(code) with response \(body)")
|
|
case .relay:
|
|
print("Relay error")
|
|
default:
|
|
print("Other error: \(error.localizedDescription)")
|
|
}
|
|
}
|
|
```
|
|
- id: passing-custom-headers
|
|
name: Passing custom headers
|
|
description: |
|
|
You can pass custom headers to your function. Note: supabase-swift automatically passes the `Authorization` header with the signed-in user's JWT.
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let response = try await supabase.functions.invoke(
|
|
"hello",
|
|
options: FunctionInvokeOptions(
|
|
headers: [
|
|
HTTPField.Name("my-custom-header")!: "my-custom-header-value"
|
|
]
|
|
)
|
|
)
|
|
```
|
|
- id: regional-invocation
|
|
name: Invoking a Function in the UsEast1 region
|
|
description: |
|
|
Here are the available regions:
|
|
- `FunctionRegion.apNortheast1`
|
|
- `FunctionRegion.apNortheast2`
|
|
- `FunctionRegion.apSouth1`
|
|
- `FunctionRegion.apSoutheast1`
|
|
- `FunctionRegion.apSoutheast2`
|
|
- `FunctionRegion.caCentral1`
|
|
- `FunctionRegion.euCentral1`
|
|
- `FunctionRegion.euCentral2`
|
|
- `FunctionRegion.euWest1`
|
|
- `FunctionRegion.euWest2`
|
|
- `FunctionRegion.euWest3`
|
|
- `FunctionRegion.saEast1`
|
|
- `FunctionRegion.usEast1`
|
|
- `FunctionRegion.usWest1`
|
|
- `FunctionRegion.usWest2`
|
|
|
|
`FunctionRegion` is an open set. For a region with no constant, pass `FunctionRegion(rawValue: "region-name")` or a string literal. To set a default region for every call, use `SupabaseClient.Configuration.Functions(region:)`.
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let response = try await supabase.functions.invoke(
|
|
"hello",
|
|
body: .json(["foo": "bar"]),
|
|
options: FunctionInvokeOptions(
|
|
region: .usEast1
|
|
)
|
|
)
|
|
```
|
|
- id: calling-with-delete-verb
|
|
name: Calling with DELETE HTTP verb
|
|
description: |
|
|
You can also set the HTTP verb to `DELETE` when calling your Edge Function.
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let response = try await supabase.functions.invoke(
|
|
"hello",
|
|
body: .json(["foo": "bar"]),
|
|
options: FunctionInvokeOptions(
|
|
method: .delete,
|
|
headers: [
|
|
HTTPField.Name("my-custom-header")!: "my-custom-header-value"
|
|
]
|
|
)
|
|
)
|
|
```
|
|
- id: calling-with-get-verb
|
|
name: Calling with GET HTTP verb
|
|
description: |
|
|
You can also set the HTTP verb to `GET` when calling your Edge Function.
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let response = try await supabase.functions.invoke(
|
|
"hello",
|
|
options: FunctionInvokeOptions(
|
|
method: .get,
|
|
headers: [
|
|
HTTPField.Name("my-custom-header")!: "my-custom-header-value"
|
|
]
|
|
)
|
|
)
|
|
```
|
|
- id: additional-query-params
|
|
name: Pass additional query params
|
|
description: |
|
|
You can pass additional query params when invoking a function.
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let response = try await supabase.functions.invoke(
|
|
"hello",
|
|
options: FunctionInvokeOptions(
|
|
query: [URLQueryItem(name: "key", value: "value")]
|
|
)
|
|
)
|
|
```
|
|
- id: invocation-with-timeout-override
|
|
name: Invocation with a custom timeout
|
|
description: |
|
|
Override the default 150-second idle timeout for a single invocation by passing `timeout`.
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let response = try await supabase.functions.invoke(
|
|
"hello",
|
|
body: .json(["foo": "bar"]),
|
|
options: FunctionInvokeOptions(
|
|
timeout: .seconds(30)
|
|
)
|
|
)
|
|
```
|
|
|
|
- id: invoke-stream
|
|
title: stream()
|
|
description: |
|
|
Invoke a Supabase Edge Function and read the response body as it arrives. Use it for `text/event-stream` responses and large downloads.
|
|
notes: |
|
|
- `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`.
|
|
examples:
|
|
- id: invocation-with-streamed-response
|
|
name: Invocation with streamed response
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
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)
|
|
}
|
|
```
|
|
|
|
- id: subscribe
|
|
title: subscribe()
|
|
notes: |
|
|
- 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](/docs/guides/api#realtime-api-overview).
|
|
- 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.
|
|
examples:
|
|
- id: listen-to-broadcast
|
|
name: Listen to broadcast messages
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
// 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)
|
|
]
|
|
)
|
|
```
|
|
|
|
- id: listen-to-broadcast-typed
|
|
name: Listen to broadcast messages with a typed payload
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
struct CursorPosition: Codable {
|
|
let x: Double
|
|
let y: Double
|
|
}
|
|
|
|
// 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()
|
|
|
|
let task = Task {
|
|
for await message in broadcastStream {
|
|
let position = try message.decode(as: CursorPosition.self)
|
|
print("Cursor position received", position)
|
|
}
|
|
}
|
|
|
|
try await channel.broadcast(
|
|
event: "cursor-pos",
|
|
payload: CursorPosition(x: 0.5, y: 0.5)
|
|
)
|
|
|
|
// Stop listening some time later
|
|
task.cancel()
|
|
```
|
|
|
|
- id: broadcast-with-replay
|
|
name: Configure broadcast with replay
|
|
description: |
|
|
Replay allows you to receive messages that were broadcast since a specific date. It works on private channels only. `isReplayed` on each message tells you whether the server replayed it.
|
|
isSpotlight: false
|
|
code: |
|
|
```swift
|
|
let channel = await supabase.channel("my-channel") {
|
|
$0.isPrivate = true
|
|
$0.broadcast.acknowledgesMessages = true
|
|
$0.broadcast.receivesOwnMessages = true
|
|
$0.broadcast.replay = .init(
|
|
since: Date(timeIntervalSinceNow: -3600),
|
|
limit: 100
|
|
)
|
|
}
|
|
|
|
let messages = await channel.broadcasts(event: "*")
|
|
|
|
try await channel.subscribe()
|
|
|
|
for await message in messages where message.isReplayed {
|
|
print("Replayed message: \(message.id?.uuidString ?? "")")
|
|
}
|
|
```
|
|
|
|
- id: listen-to-presence-updates
|
|
name: Listen to presence updates
|
|
description: |
|
|
`presenceChanges()` yields the entries that joined and left in each sync, by presence key. To show who is online, `presenceStates()` yields the whole state after every change.
|
|
code: |
|
|
```swift
|
|
struct UserStatus: Codable {
|
|
let username: String
|
|
}
|
|
|
|
let channel = await supabase.channel("channelId")
|
|
|
|
let presenceChanges = await channel.presenceChanges()
|
|
|
|
try await channel.subscribe()
|
|
|
|
Task {
|
|
for await change in presenceChanges {
|
|
let joins = try change.joins.values.flatMap { $0 }.map { try $0.decode(as: UserStatus.self) }
|
|
let leaves = try change.leaves.values.flatMap { $0 }.map { try $0.decode(as: UserStatus.self) }
|
|
}
|
|
}
|
|
|
|
// Send your own state
|
|
try await channel.track(UserStatus(username: "John"))
|
|
```
|
|
|
|
- id: listen-to-presence-state
|
|
name: Listen to the presence state
|
|
code: |
|
|
```swift
|
|
struct UserStatus: Codable {
|
|
let username: String
|
|
}
|
|
|
|
let channel = await supabase.channel("channelId") {
|
|
$0.presence.key = userID.uuidString
|
|
}
|
|
|
|
let presenceStates = await channel.presenceStates()
|
|
|
|
try await channel.subscribe()
|
|
|
|
// Send your own state
|
|
try await channel.track(UserStatus(username: "John"))
|
|
|
|
for await state in presenceStates {
|
|
let online: [String: [UserStatus]] = try state.decode()
|
|
print("Online users:", online)
|
|
}
|
|
```
|
|
|
|
- id: listen-to-all-database-changes
|
|
name: Listen to all database changes
|
|
code: |
|
|
```swift
|
|
let channel = await supabase.channel("channelId")
|
|
|
|
let changeStream = await channel.postgresChanges(schema: "public")
|
|
|
|
try await channel.subscribe()
|
|
|
|
for await change in changeStream {
|
|
switch change.kind {
|
|
case .delete: print("Deleted: \(change.oldRecord?.values ?? [:])")
|
|
case .insert: print("Inserted: \(change.record?.values ?? [:])")
|
|
case .update: print("Updated: \(change.oldRecord?.values ?? [:]) with \(change.record?.values ?? [:])")
|
|
default: break
|
|
}
|
|
}
|
|
```
|
|
- id: listen-to-a-specific-table
|
|
name: Listen to a specific table
|
|
code: |
|
|
```swift
|
|
let channel = await supabase.channel("channelId")
|
|
|
|
let changeStream = await channel.postgresChanges(
|
|
schema: "public",
|
|
table: "users"
|
|
)
|
|
|
|
try await channel.subscribe()
|
|
|
|
for await change in changeStream {
|
|
switch change.kind {
|
|
case .delete: print("Deleted: \(change.oldRecord?.values ?? [:])")
|
|
case .insert: print("Inserted: \(change.record?.values ?? [:])")
|
|
case .update: print("Updated: \(change.oldRecord?.values ?? [:]) with \(change.record?.values ?? [:])")
|
|
default: break
|
|
}
|
|
}
|
|
```
|
|
- id: listen-to-a-specific-table-typed
|
|
name: Listen to a specific table with a typed row
|
|
description: |
|
|
`postgresChanges(of:)` binds each change to a row type. Call `row()` to decode the record. A row that does not decode throws from `row()` and does not end the stream. `oldRecord` stays untyped, because without `REPLICA IDENTITY FULL` it holds only the primary key.
|
|
code: |
|
|
```swift
|
|
struct User: Decodable {
|
|
let id: Int
|
|
let username: String
|
|
}
|
|
|
|
let channel = await supabase.channel("channelId")
|
|
|
|
let changeStream = await channel.postgresChanges(
|
|
of: User.self,
|
|
schema: "public",
|
|
table: "users"
|
|
)
|
|
|
|
try await channel.subscribe()
|
|
|
|
for await change in changeStream {
|
|
switch change.kind {
|
|
case .insert, .update:
|
|
do {
|
|
let user = try change.row()
|
|
print("Upserted: \(user)")
|
|
} catch {
|
|
print("Could not decode the row: \(error)")
|
|
}
|
|
case .delete: print("Deleted id: \(change.oldRecord?["id"]?.intValue ?? 0)")
|
|
default: break
|
|
}
|
|
}
|
|
```
|
|
- id: listen-to-inserts
|
|
name: Listen to inserts
|
|
code: |
|
|
```swift
|
|
let channel = await supabase.channel("channelId")
|
|
|
|
let insertions = await channel.postgresChanges(
|
|
event: .insert,
|
|
schema: "public",
|
|
table: "users"
|
|
)
|
|
|
|
try await channel.subscribe()
|
|
|
|
for await insert in insertions {
|
|
print("Inserted: \(insert.record?.values ?? [:])")
|
|
}
|
|
```
|
|
- id: listen-to-updates
|
|
name: Listen to updates
|
|
description: |
|
|
By default, Supabase will send only the updated record. If you want to receive the previous values as well you can
|
|
enable full replication for the table you are listening to:
|
|
|
|
```sql
|
|
alter table "your_table" replica identity full;
|
|
```
|
|
code: |
|
|
```swift
|
|
let channel = await supabase.channel("channelId")
|
|
|
|
let updates = await channel.postgresChanges(
|
|
event: .update,
|
|
schema: "public",
|
|
table: "users"
|
|
)
|
|
|
|
try await channel.subscribe()
|
|
|
|
for await update in updates {
|
|
print("Updated: \(update.oldRecord?.values ?? [:]) with \(update.record?.values ?? [:])")
|
|
}
|
|
```
|
|
- id: listen-to-deletes
|
|
name: Listen to deletes
|
|
description: |
|
|
By default, Supabase does not send deleted records. If you want to receive the deleted record you can
|
|
enable full replication for the table you are listening to:
|
|
|
|
```sql
|
|
alter table "your_table" replica identity full;
|
|
```
|
|
code: |
|
|
```swift
|
|
let channel = await supabase.channel("channelId")
|
|
|
|
let deletions = await channel.postgresChanges(
|
|
event: .delete,
|
|
schema: "public",
|
|
table: "users"
|
|
)
|
|
|
|
try await channel.subscribe()
|
|
|
|
for await deletion in deletions {
|
|
print("Deleted: \(deletion.oldRecord?.values ?? [:])")
|
|
}
|
|
```
|
|
- id: listening-to-row-level-changes
|
|
name: Listen to row level changes
|
|
description: |
|
|
You can only filter delete events when the table's replica identity is `full`. Run `alter table users replica identity full;` first.
|
|
code: |
|
|
```swift
|
|
let channel = await supabase.channel("channelId")
|
|
|
|
let deletions = await channel.postgresChanges(
|
|
event: .delete,
|
|
schema: "public",
|
|
table: "users",
|
|
filter: .eq("id", value: 1)
|
|
)
|
|
|
|
try await channel.subscribe()
|
|
|
|
for await deletion in deletions {
|
|
print("Deleted: \(deletion.oldRecord?.values ?? [:])")
|
|
}
|
|
```
|
|
- id: stop-listening
|
|
name: Stop listening
|
|
description: |
|
|
Cancel the task that iterates a stream to stop listening. The channel stays joined until you call `unsubscribe()` or remove it.
|
|
code: |
|
|
```swift
|
|
let channel = await supabase.channel("channelId")
|
|
|
|
let insertions = await channel.postgresChanges(
|
|
event: .insert,
|
|
schema: "public",
|
|
table: "users"
|
|
)
|
|
|
|
try await channel.subscribe()
|
|
|
|
let task = Task {
|
|
for await insert in insertions {
|
|
print("Inserted: \(insert.record?.values ?? [:])")
|
|
}
|
|
}
|
|
|
|
// Some time later
|
|
task.cancel()
|
|
await supabase.removeChannel(channel)
|
|
```
|
|
|
|
- id: remove-channel
|
|
description: |
|
|
Unsubscribes and removes Realtime channel from Realtime client.
|
|
title: 'removeChannel()'
|
|
notes: |
|
|
- 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.
|
|
examples:
|
|
- id: removes-a-channel
|
|
name: Remove a channel
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let channel = await supabase.channel("channelId")
|
|
|
|
//...
|
|
await supabase.removeChannel(channel)
|
|
```
|
|
- id: unsubscribe-channel
|
|
name: Unsubscribe from a channel
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let channel = await supabase.channel("channelId")
|
|
|
|
//...
|
|
await channel.unsubscribe()
|
|
```
|
|
- id: remove-all-channels
|
|
title: removeAllChannels()
|
|
$ref: '@supabase/supabase-js.index.SupabaseClient.removeAllChannels'
|
|
notes: |
|
|
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`.
|
|
examples:
|
|
- id: remove-all-channels
|
|
name: Remove all channels
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
await supabase.removeAllChannels()
|
|
```
|
|
- id: get-channels
|
|
title: channels
|
|
$ref: '@supabase/supabase-js.index.SupabaseClient.getChannels'
|
|
notes: |
|
|
Returns all Realtime channels that the client created and has not removed. The read is `async`, and the order is not specified.
|
|
examples:
|
|
- id: get-all-channels
|
|
name: Get all channels
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let channels = await supabase.channels
|
|
```
|
|
- id: file-buckets
|
|
title: 'Overview'
|
|
notes: |
|
|
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`.
|
|
# - id: analytics-buckets
|
|
# title: 'Overview'
|
|
# notes: |
|
|
# This section contains methods for working with Analytics Buckets.
|
|
# - id: vector-buckets
|
|
# title: 'Overview'
|
|
# notes: |
|
|
# This section contains methods for working with Vector Buckets.
|
|
|
|
- id: list-buckets
|
|
title: listBuckets()
|
|
notes: |
|
|
- RLS policy permissions required:
|
|
- `buckets` table permissions: `select`
|
|
- `objects` table permissions: none
|
|
- Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works
|
|
examples:
|
|
- id: list-buckets
|
|
name: List buckets
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let buckets = try await supabase.storage
|
|
.listBuckets()
|
|
```
|
|
- id: list-buckets-with-options
|
|
name: List buckets with options
|
|
code: |
|
|
```swift
|
|
let buckets = try await supabase.storage
|
|
.listBuckets(
|
|
options: BucketListOptions(
|
|
limit: 10,
|
|
sortBy: .createdAt,
|
|
order: .descending
|
|
)
|
|
)
|
|
```
|
|
|
|
- id: get-bucket
|
|
title: bucket()
|
|
notes: |
|
|
- RLS policy permissions required:
|
|
- `buckets` table permissions: `select`
|
|
- `objects` table permissions: none
|
|
- Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works
|
|
examples:
|
|
- id: get-bucket
|
|
name: Get bucket
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let bucket = try await supabase.storage
|
|
.bucket("avatars")
|
|
```
|
|
|
|
- id: create-bucket
|
|
title: createBucket()
|
|
notes: |
|
|
- RLS policy permissions required:
|
|
- `buckets` table permissions: `insert`
|
|
- `objects` table permissions: none
|
|
- Refer to the [Storage guide](/docs/guides/storage/security/access-control) 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.
|
|
examples:
|
|
- id: create-bucket
|
|
name: Create bucket
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
try await supabase.storage
|
|
.createBucket(
|
|
"avatars",
|
|
options: CreateBucketOptions(
|
|
isPublic: false,
|
|
fileSizeLimit: .megabytes(1),
|
|
allowedMimeTypes: ["image/png"]
|
|
)
|
|
)
|
|
```
|
|
|
|
- id: empty-bucket
|
|
title: emptyBucket()
|
|
notes: |
|
|
- RLS policy permissions required:
|
|
- `buckets` table permissions: `select`
|
|
- `objects` table permissions: `select` and `delete`
|
|
- Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works
|
|
examples:
|
|
- id: empty-bucket
|
|
name: Empty bucket
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
try await supabase.storage
|
|
.emptyBucket("avatars")
|
|
```
|
|
- id: update-bucket
|
|
title: updateBucket()
|
|
notes: |
|
|
- RLS policy permissions required:
|
|
- `buckets` table permissions: `select` and `update`
|
|
- `objects` table permissions: none
|
|
- Refer to the [Storage guide](/docs/guides/storage/security/access-control) 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.
|
|
examples:
|
|
- id: update-bucket
|
|
name: Update bucket
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
try await supabase.storage
|
|
.updateBucket(
|
|
"avatars",
|
|
options: UpdateBucketOptions(
|
|
isPublic: false,
|
|
fileSizeLimit: .megabytes(1),
|
|
allowedMimeTypes: ["image/png"]
|
|
)
|
|
)
|
|
```
|
|
|
|
- id: delete-bucket
|
|
title: deleteBucket()
|
|
notes: |
|
|
- RLS policy permissions required:
|
|
- `buckets` table permissions: `select` and `delete`
|
|
- `objects` table permissions: none
|
|
- Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works
|
|
examples:
|
|
- id: delete-bucket
|
|
name: Delete bucket
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
try await supabase.storage
|
|
.deleteBucket("avatars")
|
|
```
|
|
|
|
- id: from-upload
|
|
title: from.upload()
|
|
notes: |
|
|
- 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](/docs/guides/storage/security/access-control) 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.
|
|
examples:
|
|
- id: upload-file
|
|
name: Upload file
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
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
|
|
)
|
|
)
|
|
```
|
|
- id: upload-file-from-url
|
|
name: Upload file from disk
|
|
code: |
|
|
```swift
|
|
let fileURL = URL(fileURLWithPath: "/path/to/avatar1.png")
|
|
|
|
try await supabase.storage
|
|
.from("avatars")
|
|
.upload(path: "public/avatar1.png", fileURL: fileURL)
|
|
```
|
|
|
|
- id: from-update
|
|
title: from.update()
|
|
notes: |
|
|
- RLS policy permissions required:
|
|
- `buckets` table permissions: none
|
|
- `objects` table permissions: `update` and `select`
|
|
- Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works
|
|
- `update` always replaces the file and ignores `upsert`. The file must already exist.
|
|
examples:
|
|
- id: update-file
|
|
name: Update file
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
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))
|
|
)
|
|
)
|
|
```
|
|
|
|
- id: from-move
|
|
title: from.move()
|
|
notes: |
|
|
- RLS policy permissions required:
|
|
- `buckets` table permissions: none
|
|
- `objects` table permissions: `update` and `select`
|
|
- Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works
|
|
- Pass `toBucket:` to move the file into a different bucket.
|
|
examples:
|
|
- id: move-file
|
|
name: Move file
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.storage
|
|
.from("avatars")
|
|
.move(from: "public/avatar1.png", to: "private/avatar2.png")
|
|
```
|
|
- id: move-file-to-another-bucket
|
|
name: Move file to another bucket
|
|
code: |
|
|
```swift
|
|
try await supabase
|
|
.storage
|
|
.from("avatars")
|
|
.move(from: "public/avatar1.png", to: "avatar1.png", toBucket: "archive")
|
|
```
|
|
|
|
- id: from-copy
|
|
title: from.copy()
|
|
notes: |
|
|
- RLS policy permissions required:
|
|
- `buckets` table permissions: none
|
|
- `objects` table permissions: `insert` and `select`
|
|
- Refer to the [Storage guide](/docs/guides/storage/security/access-control) 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.
|
|
examples:
|
|
- id: copy-file
|
|
name: Copy file
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let copy = try await supabase
|
|
.storage
|
|
.from("avatars")
|
|
.copy(from: "public/avatar1.png", to: "private/avatar2.png")
|
|
|
|
print(copy.fullPath) // "avatars/private/avatar2.png"
|
|
```
|
|
|
|
- id: from-create-signed-url
|
|
title: from.createSignedURL()
|
|
notes: |
|
|
- RLS policy permissions required:
|
|
- `buckets` table permissions: none
|
|
- `objects` table permissions: `select`
|
|
- Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works
|
|
- `expiresIn` is a `Duration`. Storage rejects a value less than one second.
|
|
examples:
|
|
- id: create-signed-url
|
|
name: Create Signed URL
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let signedURL = try await supabase.storage
|
|
.from("avatars")
|
|
.createSignedURL(path: "folder/avatar1.png", expiresIn: .seconds(60))
|
|
```
|
|
- id: create-signed-url-with-transformations
|
|
name: Create a signed URL for an asset with transformations
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let signedURL = try await supabase.storage
|
|
.from("avatars")
|
|
.createSignedURL(
|
|
path: "folder/avatar1.png",
|
|
expiresIn: .seconds(60),
|
|
options: SignedURLOptions(
|
|
transform: ImageTransform(
|
|
width: 100,
|
|
height: 100
|
|
)
|
|
)
|
|
)
|
|
```
|
|
- id: create-signed-url-with-download
|
|
name: Create a signed URL which triggers the download of the asset
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let signedURL = try await supabase.storage
|
|
.from("avatars")
|
|
.createSignedURL(
|
|
path: "folder/avatar1.png",
|
|
expiresIn: .seconds(60),
|
|
options: SignedURLOptions(download: .withOriginalName)
|
|
)
|
|
```
|
|
note: |
|
|
Use `.withOriginalName` to download with the original file name, or `.named("custom.png")` to specify a custom file name.
|
|
|
|
- id: from-create-signed-urls
|
|
title: from.createSignedURLs()
|
|
notes: |
|
|
- RLS policy permissions required:
|
|
- `buckets` table permissions: none
|
|
- `objects` table permissions: `select`
|
|
- Refer to the [Storage guide](/docs/guides/storage/security/access-control) 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.
|
|
examples:
|
|
- id: create-signed-urls
|
|
name: Create Signed URLs
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
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)
|
|
}
|
|
}
|
|
```
|
|
|
|
- id: from-create-signed-upload-url
|
|
title: from.createSignedUploadURL()
|
|
description: |
|
|
Create a signed upload URL that can be used to upload files to a bucket.
|
|
notes: |
|
|
- RLS policy permissions required:
|
|
- `buckets` table permissions: none
|
|
- `objects` table permissions: `insert`
|
|
- Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works
|
|
- Signed upload URLs are valid for 2 hours. Pass the returned `token` to `uploadToSignedURL()`.
|
|
examples:
|
|
- id: create-signed-upload-url
|
|
name: Create signed upload URL
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let signedUpload = try await supabase.storage
|
|
.from("avatars")
|
|
.createSignedUploadURL(path: "folder/avatar1.png")
|
|
```
|
|
- id: create-signed-upload-url-with-options
|
|
name: Create signed upload URL that can replace a file
|
|
code: |
|
|
```swift
|
|
let signedUpload = try await supabase.storage
|
|
.from("avatars")
|
|
.createSignedUploadURL(
|
|
path: "folder/avatar1.png",
|
|
upsert: true
|
|
)
|
|
```
|
|
|
|
- id: from-upload-to-signed-url
|
|
title: from.uploadToSignedURL()
|
|
description: |
|
|
Upload a file to a bucket using a signed URL.
|
|
notes: |
|
|
- 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.
|
|
examples:
|
|
- id: upload-to-signed-url
|
|
name: Upload to signed URL
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
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"
|
|
)
|
|
)
|
|
```
|
|
- id: upload-file-to-signed-url
|
|
name: Upload file from URL to signed URL
|
|
code: |
|
|
```swift
|
|
let fileURL = URL(fileURLWithPath: "/path/to/file.txt")
|
|
|
|
try await supabase.storage
|
|
.from("avatars")
|
|
.uploadToSignedURL(
|
|
path: "folder/avatar1.png",
|
|
token: "your-signed-token",
|
|
fileURL: fileURL,
|
|
options: UploadOptions(
|
|
contentType: "text/plain"
|
|
)
|
|
)
|
|
```
|
|
|
|
- id: from-get-public-url
|
|
title: from.publicURL()
|
|
notes: |
|
|
- The bucket needs to be set to public, either via [updateBucket()](/docs/reference/swift/v3/storage-updatebucket) or by going to Storage on [supabase.com/dashboard](https://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](/docs/guides/storage/security/access-control) on how access control works
|
|
- `publicURL` does not throw and does not send a request.
|
|
examples:
|
|
- id: returns-the-url-for-an-asset-in-a-public-bucket
|
|
name: Returns the URL for an asset in a public bucket
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let publicURL = supabase.storage
|
|
.from("public-bucket")
|
|
.publicURL(path: "folder/avatar1.png")
|
|
```
|
|
- id: transform-asset-in-public-bucket
|
|
name: Returns the URL for an asset in a public bucket with transformations
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let publicURL = supabase.storage
|
|
.from("public-bucket")
|
|
.publicURL(
|
|
path: "folder/avatar1.png",
|
|
options: PublicURLOptions(
|
|
transform: ImageTransform(
|
|
width: 100,
|
|
height: 100
|
|
)
|
|
)
|
|
)
|
|
```
|
|
- id: download-asset-in-public-bucket
|
|
name: Returns the URL which triggers the download of an asset in a public bucket
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let publicURL = supabase.storage
|
|
.from("public-bucket")
|
|
.publicURL(
|
|
path: "folder/avatar1.png",
|
|
options: PublicURLOptions(download: .withOriginalName)
|
|
)
|
|
```
|
|
note: |
|
|
Use `.withOriginalName` to download with the original file name, or `.named("custom.png")` to specify a custom file name.
|
|
|
|
- id: from-download
|
|
title: from.download()
|
|
notes: |
|
|
- RLS policy permissions required:
|
|
- `buckets` table permissions: none
|
|
- `objects` table permissions: `select`
|
|
- Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works
|
|
- Returns a `DownloadResponse` as soon as the response headers arrive. Read the body once, with `data()` or `write(to:)`.
|
|
examples:
|
|
- id: download-file
|
|
name: Download file
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let data = try await supabase.storage
|
|
.from("avatars")
|
|
.download(path: "folder/avatar1.png")
|
|
.data()
|
|
```
|
|
- id: download-file-with-transformations
|
|
name: Download file with transformations
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let data = try await supabase.storage
|
|
.from("avatars")
|
|
.download(
|
|
path: "folder/avatar1.png",
|
|
options: DownloadOptions(
|
|
transform: ImageTransform(
|
|
width: 100,
|
|
height: 100,
|
|
quality: 80
|
|
)
|
|
)
|
|
)
|
|
.data()
|
|
```
|
|
- id: download-file-to-disk
|
|
name: Download file to disk
|
|
code: |
|
|
```swift
|
|
try await supabase.storage
|
|
.from("avatars")
|
|
.download(path: "folder/avatar1.png")
|
|
.write(to: fileURL)
|
|
```
|
|
|
|
- id: from-remove
|
|
title: from.remove()
|
|
notes: |
|
|
- RLS policy permissions required:
|
|
- `buckets` table permissions: none
|
|
- `objects` table permissions: `delete` and `select`
|
|
- Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works
|
|
- Returns the removed files as `[StorageObject]`. You can ignore the result.
|
|
examples:
|
|
- id: delete-file
|
|
name: Delete file
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
try await supabase.storage
|
|
.from("avatars")
|
|
.remove(paths: ["folder/avatar1.png"])
|
|
```
|
|
|
|
- id: from-list
|
|
title: from.list()
|
|
notes: |
|
|
- RLS policy permissions required:
|
|
- `buckets` table permissions: none
|
|
- `objects` table permissions: `select`
|
|
- Refer to the [Storage guide](/docs/guides/storage/security/access-control) 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.
|
|
examples:
|
|
- id: list-files-in-a-bucket
|
|
name: List files in a bucket
|
|
isSpotlight: true
|
|
code: |
|
|
```swift
|
|
let files = try await supabase.storage
|
|
.from("avatars")
|
|
.list(
|
|
path: "folder",
|
|
options: ListOptions(
|
|
limit: 100,
|
|
offset: 0,
|
|
sortBy: .name,
|
|
order: .ascending
|
|
)
|
|
)
|
|
```
|
|
- id: search-files-in-a-bucket
|
|
name: Search files in a bucket
|
|
code: |
|
|
```swift
|
|
let files = try await supabase.storage
|
|
.from("avatars")
|
|
.list(
|
|
path: "folder",
|
|
options: ListOptions(
|
|
limit: 100,
|
|
offset: 0,
|
|
sortBy: .name,
|
|
order: .ascending,
|
|
search: "jon"
|
|
)
|
|
)
|
|
```
|