Files
supabase/spec/supabase_js_v2.yml
T

4815 lines
148 KiB
YAML

openref: 0.1
info:
id: reference/supabase-js
title: Supabase Client
description: |
Supabase JavaScript.
definition: ../../spec/enrichments/tsdoc_v2/combined.json
specUrl: https://github.com/supabase/supabase/edit/master/spec/supabase_js_v2.yml
slugPrefix: '/'
libraries:
- id: 'JavaScript'
version: '0.0.1'
functions:
- id: initializing
title: 'Initializing'
$ref: '@supabase/supabase-js.index.SupabaseClient.constructor'
description: |
You can initialize a new Supabase client using the `createClient()` method.
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.
examples:
- id: create-client
name: createClient()
code: |
```js
import { createClient } from '@supabase/supabase-js'
// Create a single supabase client for interacting with your database
const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key')
```
- id: with-additional-parameters
name: With additional parameters
code: |
```js
import { createClient } from '@supabase/supabase-js'
const options = {
db: {
schema: 'public',
},
auth: {
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: true
},
global: {
headers: { 'x-my-custom-header': 'my-app-name' },
},
}
const supabase = createClient("https://xyzcompany.supabase.co", "public-anon-key", options)
```
- id: api-schemas
name: API schemas
code: |
```js
import { createClient } from '@supabase/supabase-js'
// Provide a custom schema. Defaults to "public".
const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key', {
db: { 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](https://app.supabase.com/project/_/settings/api) and add the schema which you want to expose to the API.
Note: each client connection can only access a single schema, so the code above can access the `other_schema` schema but cannot access the `public` schema.
- id: custom-fetch-implementation
name: Custom `fetch` implementation
code: |
```js
import { createClient } from '@supabase/supabase-js'
const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key', {
global: { fetch: fetch.bind(globalThis) }
})
```
description: |
`supabase-js` uses the [`cross-fetch`](https://www.npmjs.com/package/cross-fetch) library to make HTTP requests,
but an alternative `fetch` implementation can be provided as an option.
This is most useful in environments where `cross-fetch` is not compatible (for instance Cloudflare Workers).
- id: react-native-options
name: React Native options
code: |
```js
import { createClient } from '@supabase/supabase-js'
import AsyncStorage from "@react-native-async-storage/async-storage";
const supabase = createClient("https://xyzcompany.supabase.co", "public-anon-key", {
auth: {
storage: AsyncStorage,
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: false,
},
});
```
description: |
For React Native we recommend using `AsyncStorage` as the storage implementation for Supabase Auth.
- id: auth-api
title: 'Overview'
notes: |
- The auth methods can be accessed via the `supabase.auth` namespace.
examples:
- id: create-auth-client
name: Create auth client
isSpotlight: true
code: |
```js
import { createClient } from '@supabase/supabase-js'
const supabase = createClient(supabase_url, anon_key)
```
- id: create-auth-client-server-side
name: Create auth client (server-side)
isSpotlight: false
code: |
```js
import { createClient } from '@supabase/supabase-js'
const supabase = createClient(supabase_url, anon_key, {
auth: {
autoRefreshToken: false,
persistSession: false,
detectSessionInUrl: false
}
})
```
- id: sign-up
title: 'signUp()'
$ref: '@supabase/gotrue-js.GoTrueClient.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](https://app.supabase.com/project/_/auth/providers).
- **Confirm email** determines if users need to confirm their email address after signing up.
- If **Confirm email** is enabled, a `user` is returned but `session` is null.
- If **Confirm email** is disabled, both a `user` and a `session` are returned.
- When the user confirms their email address, they are redirected to the [`SITE_URL`](https://supabase.com/docs/reference/auth/config#site_url) by default. You can modify your `SITE_URL` or add additional redirect URLs in [your project](https://app.supabase.com/project/_/auth/url-configuration).
- If signUp() is called for an existing confirmed user:
- If **Confirm email** is enabled in [your project](https://app.supabase.com/project/_/auth/providers), an obfuscated/fake user object is returned.
- If **Confirm email** is disabled, the error message, `User already registered` is returned.
- To fetch the currently logged-in user, refer to [`getUser()`](/docs/reference/javascript/auth-getuser).
examples:
- id: sign-up
name: Sign up
isSpotlight: true
code: |
```js
const { data, error } = await supabase.auth.signUp({
email: 'example@email.com',
password: 'example-password',
})
```
- id: sign-up-with-additional-user-metadata
name: Sign up with additional user metadata
isSpotlight: false
code: |
```js
const { data, error } = await supabase.auth.signUp(
{
email: 'example@email.com',
password: 'example-password',
options: {
data: {
first_name: 'John',
age: 27,
}
}
}
)
```
- id: sign-up-with-redirect
name: Sign up with a redirect URL
description: |
- See [redirect URLs and wildcards](/docs/guides/auth/overview#redirect-urls-and-wildcards) to add additional redirect URLs to your project.
code: |
```js
const { data, error } = await supabase.auth.signUp(
{
email: 'example@email.com',
password: 'example-password',
options: {
emailRedirectTo: 'https://example.com/welcome'
}
}
)
```
- id: sign-in-with-password
title: 'signInWithPassword()'
$ref: '@supabase/gotrue-js.GoTrueClient.signInWithPassword'
notes: |
- Requires either an email and password or a phone number and password.
examples:
- id: sign-in-with-email-and-password
name: Sign in with email and password
isSpotlight: true
code: |
```js
const { data, error } = await supabase.auth.signInWithPassword({
email: 'example@email.com',
password: 'example-password',
})
```
- id: sign-in-with-phone-and-password
name: Sign in with phone and password
isSpotlight: false
code: |
```js
const { data, error } = await supabase.auth.signInWithPassword({
phone: '+13334445555',
password: 'some-password',
})
// After receiving a SMS with a OTP.
const { data, error } = await supabase.auth.verifyOtp({
phone: '+13334445555',
token: '123456',
})
```
- id: sign-in-with-otp
title: 'signInWithOtp()'
$ref: '@supabase/gotrue-js.GoTrueClient.signInWithOtp'
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 behaviour, you can set `shouldCreateUser` in `SignInWithPasswordlessCredentials.options` to `false`.
- 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.
- The magic link's destination URL is determined by the [`SITE_URL`](/docs/reference/auth/config#site_url).
- See [redirect URLs and wildcards](/docs/guides/auth/overview#redirect-urls-and-wildcards) to add additional redirect URLs to your project.
- Magic links and OTPs share the same implementation. To send users a one-time code instead of a magic link, [modify the magic link email template](https://app.supabase.com/project/_/auth/templates) to include `{{ .Token }}` instead of `{{ .ConfirmationURL }}`.
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: |
```js
const { data, error } = await supabase.auth.signInWithOtp({
email: 'example@email.com',
options: {
emailRedirectTo: 'https://example.com/welcome'
}
})
```
- 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: |
```js
const { data, error } = await supabase.auth.signInWithOtp({
phone: '+13334445555',
})
```
- id: sign-in-with-oauth
title: 'signInWithOAuth()'
$ref: '@supabase/gotrue-js.GoTrueClient.signInWithOAuth'
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).
examples:
- id: sign-in-using-a-third-party-provider
name: Sign in using a third-party provider
isSpotlight: true
code: |
```js
const { data, error } = await supabase.auth.signInWithOAuth({
provider: 'github'
})
```
- id: sign-in-using-a-third-party-provider-with-redirect
name: Sign in using a third-party provider with redirect
isSpotlight: false
description: |
- When the third-party provider successfully authenticates the user, the provider redirects the user to the URL specified in the `redirectTo` parameter. This parameter defaults to the [`SITE_URL`](/docs/reference/auth/config#site_url). It does not redirect the user immediately after invoking this method.
- See [redirect URLs and wildcards](/docs/guides/auth/overview#redirect-urls-and-wildcards) to add additional redirect URLs to your project.
code: |
```js
const { data, error } = await supabase.auth.signInWithOAuth({
provider: 'github'
options: {
redirectTo: 'https://example.com/welcome'
}
})
```
- 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 space-separated 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: |
```js
const { data, error } = await supabase.auth.signInWithOAuth({
provider: 'github'
options: {
scopes: 'repo gist notifications'
}
})
const oAuthToken = data.session.provider_token // use to access provider API
```
- id: sign-out
title: 'signOut()'
$ref: '@supabase/gotrue-js.GoTrueClient.signOut'
notes: |
- In order to use the `signOut()` method, the user needs to be signed in first.
examples:
- id: sign-out
name: Sign out
isSpotlight: true
code: |
```js
const { error } = await supabase.auth.signOut()
```
- id: verify-otp
title: 'verifyOtp()'
$ref: '@supabase/gotrue-js.GoTrueClient.verifyOtp'
notes: |
- The `verifyOtp` method takes in different verification types. If a phone number is used, the type can either be `sms` or `phone_change`. If an email address is used, the type can be one of the following: `signup`, `magiclink`, `recovery`, `invite` or `email_change`.
- The verification type used should be determined based on the corresponding auth method called before `verifyOtp` to sign up / sign-in a user.
examples:
- id: verify-sms-one-time-password(otp)
name: Verify Sms One-Time Password (OTP)
isSpotlight: true
code: |
```js
const { data, error } = await supabase.auth.verifyOtp({ phone, token, type: 'sms'})
```
- id: verify-signup-one-time-password(otp)
name: Verify Signup One-Time Password (OTP)
isSpotlight: false
code: |
```js
const { data, error } = await supabase.auth.verifyOtp({ email, token, type: 'signup'})
```
- id: get-session
title: 'getSession()'
$ref: '@supabase/gotrue-js.GoTrueClient.getSession'
examples:
- id: get-the-session-data
name: Get the session data
isSpotlight: true
code: |
```js
const { data, error } = await supabase.auth.getSession()
```
- id: get-user
title: 'getUser()'
$ref: '@supabase/gotrue-js.GoTrueClient.getUser'
notes: |
- This method gets the user object from the current session.
- Fetches the user object from the database instead of local session.
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: |
```js
const { data: { user } } = await supabase.auth.getUser()
```
- 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: |
```js
const { data: { user } } = await supabase.auth.getUser(jwt)
```
- id: update-user
title: 'updateUser()'
$ref: '@supabase/gotrue-js.GoTrueClient.updateUser'
notes: |
- In order to use the `updateUser()` method, the user needs to be signed in first.
- 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://app.supabase.com/project/_/auth/providers).
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: |
```js
const { data, error } = await supabase.auth.updateUser({email: 'new@email.com'})
```
- id: update-the-password-for-an-authenticated-user
name: Update the password for an authenticated user
isSpotlight: false
code: |
```js
const { data, error } = await supabase.auth.updateUser({password: 'new password'})
```
- id: update-the-users-metadata
name: Update the user's metadata
isSpotlight: true
code: |
```js
const { data, error } = await supabase.auth.updateUser({
data: { hello: 'world' }
})
```
- id: set-session
title: 'setSession()'
$ref: '@supabase/gotrue-js.GoTrueClient.setSession'
notes: |
- `setSession()` takes in a refresh token and uses it to get a new session.
- The refresh token can only be used once to obtain a new session.
- [Refresh token rotation](/docs/reference/auth/config#refresh_token_rotation_enabled) is enabled by default on all projects to guard against replay attacks.
- You can configure the [`REFRESH_TOKEN_REUSE_INTERVAL`](https://supabase.com/docs/reference/auth/config#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: Refresh the session
description: Sets the session data from refresh_token and returns current session or an error if the refresh_token is invalid.
isSpotlight: true
code: |
```js
const { data, error } = supabase.auth.setSession({
access_token,
refresh_token
})
```
- id: refresh-session
title: 'refreshSession()'
$ref: '@supabase/gotrue-js.GoTrueClient.refreshSession'
notes: |
- This method will refresh the session whether the current one is expired or not.
examples:
- id: refresh-session-using-the-current-session
name: Refresh session using the current session
isSpotlight: true
code: |
```js
const { data, error } = await supabase.auth.refreshSession()
const { session, user } = data
```
- id: refresh-session-using-a-passed-in-session
name: Refresh session using a refresh token
isSpotlight: false
code: |
```js
const { data, error } = await supabase.auth.refreshSession({ refresh_token })
const { session, user } = data
```
- id: on-auth-state-change
title: 'onAuthStateChange()'
$ref: '@supabase/gotrue-js.GoTrueClient.onAuthStateChange'
notes: |
- Types of auth events: `SIGNED_IN`, `SIGNED_OUT`, `TOKEN_REFRESHED`, `USER_UPDATED`, `PASSWORD_RECOVERY`
- Currently, `onAuthStateChange()` does not work across tabs.
For instance, in the case of a password reset flow, the original tab which requested for the password reset link will not receive the `SIGNED_IN` and `PASSWORD_RECOVERY` event when the user clicks on the link.
examples:
- id: listen-to-auth-changes
name: Listen to auth changes
isSpotlight: true
code: |
```js
supabase.auth.onAuthStateChange((event, session) => {
console.log(event, session)
})
```
- id: listen-to-password-recovery-events
name: Listen to password recovery events
code: |
```js
supabase.auth.onAuthStateChange((event, session) => {
if (event == 'PASSWORD_RECOVERY') {
console.log('PASSWORD_RECOVERY', session)
// show screen to update user's password
showPasswordResetScreen(true)
}
})
```
- id: listen-to-sign-in
name: Listen to sign in
code: |
```js
supabase.auth.onAuthStateChange((event, session) => {
if (event == 'SIGNED_IN') console.log('SIGNED_IN', session)
})
```
- id: listen-to-sign-out
name: Listen to sign out
code: |
```js
supabase.auth.onAuthStateChange((event, session) => {
if (event == 'SIGNED_OUT') console.log('SIGNED_OUT', session)
})
```
- id: listen-to-token-refresh
name: Listen to token refresh
code: |
```js
supabase.auth.onAuthStateChange((event, session) => {
if (event == 'TOKEN_REFRESHED') console.log('TOKEN_REFRESHED', session)
})
```
- id: listen-to-user-updates
name: Listen to user updates
code: |
```js
supabase.auth.onAuthStateChange((event, session) => {
if (event == 'USER_UPDATED') console.log('USER_UPDATED', session)
})
```
- id: mfa-enroll
title: 'mfa.enroll()'
$ref: '@supabase/gotrue-js.GoTrueMFAApi.enroll'
notes: |
- Currently, `totp` is the only supported `factorType`. The returned `id` should be used to create a challenge.
- To create a challenge, see [`mfa.challenge()`](/docs/reference/javascript/auth-mfa-challenge).
- To verify a challenge, see [`mfa.verify()`](/docs/reference/javascript/auth-mfa-verify).
- To create and verify a challenge in a single step, see [`mfa.challengeAndVerify()`](/docs/reference/javascript/auth-mfa-challengeandverify).
- To generate a QR code for the `totp` secret in nextjs, you can do the following:
```html
<Image src={data.totp.qr_code} alt={data.totp.uri} layout="fill"></Image>
```
examples:
- id: enroll-totp-factor
name: Enroll a time-based, one-time password (TOTP) factor
isSpotlight: true
code: |
```js
const { data, error } = await supabase.auth.mfa.enroll({
factorType: 'totp'
})
// 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 qr_code or entering the secret into the authenticator app.
const { id, type, totp: { qr_code, secret, uri } } = data
```
- id: mfa-challenge
title: 'mfa.challenge()'
$ref: '@supabase/gotrue-js.GoTrueMFAApi.challenge'
notes: |
- An [enrolled factor](/docs/reference/javascript/auth-mfa-enroll) is required before creating a challenge.
- To verify a challenge, see [`mfa.verify()`](/docs/reference/javascript/auth-mfa-verify).
examples:
- id: create-mfa-challenge
name: Create a challenge for a factor
isSpotlight: true
code: |
```js
const { data, error } = await supabase.auth.mfa.challenge({
factorId: '34e770dd-9ff9-416c-87fa-43b31d7ef225'
})
```
- id: mfa-verify
title: 'mfa.verify()'
$ref: '@supabase/gotrue-js.GoTrueMFAApi.verify'
notes: |
- To verify a challenge, please [create a challenge](/docs/reference/javascript/auth-mfa-challenge) first.
examples:
- id: verify-challenge
name: Verify a challenge for a factor
isSpotlight: true
code: |
```js
const { data, error } = await supabase.auth.mfa.verify({
factorId: '34e770dd-9ff9-416c-87fa-43b31d7ef225',
challengeId: '4034ae6f-a8ce-4fb5-8ee5-69a5863a7c15',
code: '123456'
})
```
- id: mfa-challenge-and-verify
title: 'mfa.challengeAndVerify()'
$ref: '@supabase/gotrue-js.GoTrueMFAApi.challengeAndVerify'
notes: |
- An [enrolled factor](/docs/reference/javascript/auth-mfa-enroll) is required before invoking `challengeAndVerify()`.
- Executes [`mfa.challenge()`](/docs/reference/javascript/auth-mfa-challenge) and [`mfa.verify()`](/docs/reference/javascript/auth-mfa-verify) in a single step.
examples:
- id: challenge-and-verify
name: Create and verify a challenge for a factor
isSpotlight: true
code: |
```js
const { data, error } = await supabase.auth.mfa.challengeAndVerify({
factorId: '34e770dd-9ff9-416c-87fa-43b31d7ef225',
code: '123456'
})
```
- id: mfa-unenroll
title: 'mfa.unenroll()'
$ref: '@supabase/gotrue-js.GoTrueMFAApi.unenroll'
examples:
- id: unenroll-a-factor
name: Unenroll a factor
isSpotlight: true
code: |
```js
const { data, error } = await supabase.auth.mfa.unenroll({
factorId: '34e770dd-9ff9-416c-87fa-43b31d7ef225',
})
```
- id: mfa-get-authenticator-assurance-level
title: 'mfa.getAuthenticatorAssuranceLevel()'
$ref: '@supabase/gotrue-js.GoTrueMFAApi.getAuthenticatorAssuranceLevel'
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 `aal1`.
examples:
- id: get-aal
name: Get the AAL details of a session
isSpotlight: true
code: |
```js
const { data, error } = await supabase.auth.mfa.getAuthenticatorAssuranceLevel()
const { currentLevel, nextLevel, currentAuthenticationMethods } = data
```
- id: admin-api
title: 'Overview'
notes: |
- Any method under the `supabase.auth.admin` namespace requires a `service_role` key.
- These methods are considered admin methods and should be called on a trusted server. Never expose your `service_role` key in the browser.
examples:
- id: create-auth-admin-client
name: Create server-side auth client
isSpotlight: true
code: |
```js
import { createClient } from '@supabase/supabase-js'
const supabase = createClient(supabase_url, service_role_key, {
auth: {
autoRefreshToken: false,
persistSession: false
}
})
// Access auth admin api
const adminAuthClient = supabase.auth.admin
```
- id: get-user-by-id
title: 'getUserById()'
$ref: '@supabase/gotrue-js.GoTrueAdminApi.getUserById'
notes: |
- Fetches the user object from the database based on the user's id.
- The `getUserById()` method requires the user's id which maps to the `auth.users.id` column.
examples:
- id: fetch-the-user-object-using-the-access-token-jwt
name: Fetch the user object using the access_token jwt
isSpotlight: true
code: |
```js
const { data, error } = await supabase.auth.admin.getUserById(1)
```
- id: list-users
title: 'listUsers()'
$ref: '@supabase/gotrue-js.GoTrueAdminApi.listUsers'
notes: |
- Defaults to return 50 users per page.
examples:
- id: get-a-full-list-of-users
name: Get a page of users
isSpotlight: true
code: |
```js
const { data: { users }, error } = await supabase.auth.admin.listUsers()
```
- id: get-paginated-list-of-users
name: Paginated list of users
isSpotlight: false
code: |
```js
const { data: { users }, error } = await supabase.auth.admin.listUsers({
page: 1,
perPage: 1000
})
```
- id: create-user
title: 'createUser()'
$ref: '@supabase/gotrue-js.GoTrueAdminApi.createUser'
notes: |
- To confirm the user's email address or phone number, set `email_confirm` or `phone_confirm` to true. Both arguments default to false.
examples:
- id: create-a-new-user-with-custom-user-metadata
name: With custom user metadata
isSpotlight: true
code: |
```js
const { data, error } = await supabase.auth.admin.createUser({
email: 'user@email.com',
password: 'password',
user_metadata: { name: 'Yoda' }
})
```
- id: auto-confirm-the-users-email
name: Auto-confirm the user's email
code: |
```js
const { data, error } = await supabase.auth.admin.createUser({
email: 'user@email.com',
email_confirm: true
})
```
- id: auto-confirm-the-users-phone-number
name: Auto-confirm the user's phone number
code: |
```js
const { data, error } = await supabase.auth.admin.createUser({
phone: '1234567890',
phone_confirm: true
})
```
- id: delete-user
title: 'deleteUser()'
$ref: '@supabase/gotrue-js.GoTrueAdminApi.deleteUser'
notes: |
- The `deleteUser()` method requires the user's ID, which maps to the `auth.users.id` column.
examples:
- id: removes-a-user
name: Removes a user
isSpotlight: true
code: |
```js
const { data, error } = await supabase.auth.admin.deleteUser(
'715ed5db-f090-4b8c-a067-640ecee36aa0'
)
```
- id: invite-user-by-email
title: 'inviteUserByEmail()'
$ref: '@supabase/gotrue-js.GoTrueAdminApi.inviteUserByEmail'
notes: |
- Sends an invite link to the user's email address.
examples:
- id: invite-a-user
name: Invite a user
isSpotlight: true
code: |
```js
const { data, error } = await supabase.auth.admin.inviteUserByEmail('email@example.com')
```
- id: reset-password-for-email
title: 'resetPasswordForEmail()'
$ref: '@supabase/gotrue-js.GoTrueClient.resetPasswordForEmail'
notes: |
- The password reset flow consist of 2 broad steps: (i) Allow the user to login via the password reset link; (ii) Update the user's password.
- The `resetPasswordForEmail()` only sends a password reset link to the user's email.
To update the user's password, see [`updateUser()`](/docs/reference/javascript/auth-updateuser).
- A `SIGNED_IN` and `PASSWORD_RECOVERY` event will be emitted when the password recovery link is clicked.
You can use [`onAuthStateChange()`](/docs/reference/javascript/auth-onauthstatechange) to listen and invoke a callback function on these events.
- When the user clicks the reset link in the email they are redirected back to your application.
You can configure the URL that the user is redirected to with the `redirectTo` parameter.
See [redirect URLs and wildcards](/docs/guides/auth/overview#redirect-urls-and-wildcards) to add additional redirect URLs to your project.
- After the user has been redirected successfully, prompt them for a new password and call `updateUser()`:
```js
const { data, error } = await supabase.auth.updateUser({
password: new_password
})
```
examples:
- id: reset-password
name: Reset password
isSpotlight: true
code: |
```js
const { data, error } = await supabase.auth.resetPasswordForEmail(email, {
redirectTo: 'https://example.com/update-password',
})
```
- id: reset-password-react
name: Reset password (React)
isSpotlight: true
code: |
```js
/**
* Step 1: Send the user an email to get a password reset token.
* This email contains a link which sends the user back to your application.
*/
const { data, error } = await supabase.auth
.resetPasswordForEmail('user@email.com')
/**
* Step 2: Once the user is redirected back to your application,
* ask the user to reset their password.
*/
useEffect(() => {
supabase.auth.onAuthStateChange(async (event, session) => {
if (event == "PASSWORD_RECOVERY") {
const newPassword = prompt("What would you like your new password to be?");
const { data, error } = await supabase.auth
.updateUser({ password: newPassword })
if (data) alert("Password updated successfully!")
if (error) alert("There was an error updating your password.")
}
})
}, [])
```
- id: generate-link
title: 'generateLink()'
$ref: '@supabase/gotrue-js.GoTrueAdminApi.generateLink'
examples:
- id: generate-a-signup-link
name: Generate a signup link
isSpotlight: true
code: |
```js
const { data, error } = await supabase.auth.admin.generateLink({
type: 'signup',
email: 'email@example.com',
options: {
'password': 'secret'
}
})
```
- id: generate-an-invite-link
name: Generate an invite link
isSpotlight: false
code: |
```js
const { data, error } = await supabase.auth.admin.generateLink({
type: 'invite',
email: 'email@example.com'
})
```
- id: generate-a-magic-link
name: Generate a magic link
isSpotlight: false
code: |
```js
const { data, error } = await supabase.auth.admin.generateLink({
type: 'magiclink',
email: 'email@example.com'
})
```
- id: generate-a-recovery-link
name: Generate a recovery link
isSpotlight: false
code: |
```js
const { data, error } = await supabase.auth.admin.generateLink({
type: 'recovery',
email: 'email@example.com'
})
```
- id: generate-links-to-change-current-email-address
name: Generate links to change current email address
isSpotlight: false
code: |
```js
// generate an email change link to be sent to the current email address
const { data, error } = await supabase.auth.admin.generateLink({
type: 'email_change_current',
email: 'current.email@example.com',
newEmail: 'new.email@example.com'
})
// generate an email change link to be sent to the new email address
const { data, error } = await supabase.auth.admin.generateLink({
type: 'email_change_new',
email: 'current.email@example.com',
newEmail: 'new.email@example.com'
})
```
- id: update-user-by-id
title: 'updateUserById()'
$ref: '@supabase/gotrue-js.GoTrueAdminApi.updateUserById'
examples:
- id: updates-a-users-email
name: Updates a user's email
isSpotlight: false
code: |
```js
const { data: user, error } = await supabase.auth.admin.updateUserById(
'6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4',
{ email: 'new@email.com' }
)
```
- id: updates-a-users-password
name: Updates a user's password
isSpotlight: false
code: |
```js
const { data: user, error } = await supabase.auth.admin.updateUserById(
'6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4',
{ password: 'new_password' }
)
```
- id: updates-a-users-metadata
name: Updates a user's metadata
isSpotlight: true
code: |
```js
const { data: user, error } = await supabase.auth.admin.updateUserById(
'6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4',
{ user_metadata: { hello: 'world' } }
)
```
- id: updates-a-users-app-metadata
name: Updates a user's app_metadata
isSpotlight: false
code: |
```js
const { data: user, error } = await supabase.auth.admin.updateUserById(
'6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4',
{ app_metadata: { plan: 'trial' } }
)
```
- id: confirms-a-users-email-address
name: Confirms a user's email address
isSpotlight: false
code: |
```js
const { data: user, error } = await supabase.auth.admin.updateUserById(
'6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4',
{ email_confirm: true }
)
```
- id: confirms-a-users-phone-number
name: Confirms a user's phone number
isSpotlight: false
code: |
```js
const { data: user, error } = await supabase.auth.admin.updateUserById(
'6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4',
{ phone_confirm: true }
)
```
- id: mfa-list-factors
title: 'mfa.listFactors()'
$ref: '@supabase/gotrue-js.GoTrueAdminMFAApi.listFactors'
examples:
- id: list-factors
name: List all factors for a user
isSpotlight: true
code: |
```js
const { data, error } = await supabase.auth.admin.mfa.listFactors()
```
- id: mfa-delete-factor
title: 'mfa.deleteFactor()'
$ref: '@supabase/gotrue-js.GoTrueAdminMFAApi.deleteFactor'
examples:
- id: delete-factor
name: Delete a factor for a user
isSpotlight: true
code: |
```js
const { data, error } = await supabase.auth.admin.mfa.deleteFactor({
id: '34e770dd-9ff9-416c-87fa-43b31d7ef225',
userId: 'a89baba7-b1b7-440f-b4bb-91026967f66b',
})
```
- id: select
title: 'Fetch data: select()'
$ref: '@supabase/postgrest-js.PostgrestQueryBuilder.select'
notes: |
- By default, Supabase projects return a maximum of 1,000 rows. This setting can be changed in your project's [API settings](https://app.supabase.com/project/_/settings/api). 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 [Filters](/docs/reference/javascript/using-filters)
- `select()` can be combined with [Modifiers](/docs/reference/javascript/using-modifiers)
- `apikey` is a reserved keyword if you're using the [Supabase Platform](/docs/guides/platform) and [should be avoided as a column name](https://github.com/supabase/supabase/issues/5465).
examples:
- id: getting-your-data
name: Getting your data
code: |
```js
const { data, error } = await supabase
.from('countries')
.select()
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
insert into
countries (id, name)
values
(1, 'Afghanistan'),
(2, 'Albania'),
(3, 'Algeria');
```
response: |
```json
{
"data": [
{
"id": 1,
"name": "Afghanistan"
},
{
"id": 2,
"name": "Albania"
},
{
"id": 3,
"name": "Algeria"
}
],
"status": 200,
"statusText": "OK"
}
```
- id: selecting-specific-columns
name: Selecting specific columns
code: |
```js
const { data, error } = await supabase
.from('countries')
.select('name')
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
insert into
countries (id, name)
values
(1, 'Afghanistan'),
(2, 'Albania'),
(3, 'Algeria');
```
response: |
```json
{
"data": [
{
"name": "Afghanistan"
},
{
"name": "Albania"
},
{
"name": "Algeria"
}
],
"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: |
```js
const { data, error } = await supabase
.from('countries')
.select(`
name,
cities (
name
)
`)
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
create table
cities (
id int8 primary key,
country_id int8 not null references countries,
name text
);
insert into
countries (id, name)
values
(1, 'Germany'),
(2, 'Indonesia');
insert into
cities (id, country_id, name)
values
(1, 2, 'Bali'),
(2, 1, 'Munich');
```
response: |
```json
{
"data": [
{
"name": "Germany",
"cities": [
{
"name": "Munich"
}
]
},
{
"name": "Indonesia",
"cities": [
{
"name": "Bali"
}
]
}
],
"status": 200,
"statusText": "OK"
}
```
- id: query-foreign-tables-through-a-join-table
name: Query foreign tables through a join table
code: |
```ts
const { data, error } = await supabase
.from('users')
.select(`
name,
teams (
name
)
`)
```
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: |
```ts
const { data, error } = await supabase
.from('messages')
.select(`
content,
from:sender_id(name),
to:receiver_id(name)
`)
```
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: |
```ts
const { data, error } = await supabase
.from('cities')
.select('name, countries(*)')
.eq('countries.name', 'Estonia')
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
create table
cities (
id int8 primary key,
country_id int8 not null references countries,
name text
);
insert into
countries (id, name)
values
(1, 'Germany'),
(2, 'Indonesia');
insert into
cities (id, country_id, name)
values
(1, 2, 'Bali'),
(2, 1, 'Munich');
```
response: |
```json
{
"data": [
{
"name": "Bali",
"countries": null
},
{
"name": "Munich",
"countries": 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: |
```ts
const { data, error } = await supabase
.from('countries')
.select(`*, cities(count)`)
```
data:
sql: |
```sql
create table countries (
"id" "uuid" primary key default "extensions"."uuid_generate_v4"() not null,
"name" text
);
create table cities (
"id" "uuid" primary key default "extensions"."uuid_generate_v4"() not null,
"name" text,
"country_id" "uuid" references public.countries on delete cascade
);
with country as (
insert into countries (name)
values ('united kingdom') returning id
)
insert into cities (name, country_id) values
('London', (select id from country)),
('Manchester', (select id from country)),
('Liverpool', (select id from country)),
('Bristol', (select id from country));
```
response: |
```json
[
{
"id": "693694e7-d993-4360-a6d7-6294e325d9b6",
"name": "United Kingdom",
"cities": [
{
"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: |
```ts
const { count, error } = await supabase
.from('countries')
.select('*', { count: 'exact', head: true })
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
insert into
countries (id, name)
values
(1, 'Afghanistan'),
(2, 'Albania'),
(3, 'Algeria');
```
response: |
```json
{
"count": 3,
"status": 200,
"statusText": "OK"
}
```
description: |
You can get the number of rows by using the
[count](/docs/reference/javascript/select#parameters) option.
hideCodeBlock: true
- id: querying-json-data
name: Querying JSON data
code: |
```ts
const { data, error } = await supabase
.from('users')
.select(`
id, name,
address->city
`)
```
data:
sql: |
```sql
create table
users (
id int8 primary key,
name text,
address jsonb
);
insert into
users (id, name, address)
values
(1, 'Avdotya', '{"city":"Saint Petersburg"}');
```
response: |
```json
{
"data": [
{
"id": 1,
"name": "Avdotya",
"city": "Saint Petersburg"
}
],
"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: insert
title: 'Create data: insert()'
$ref: '@supabase/postgrest-js.PostgrestQueryBuilder.insert'
examples:
- id: create-a-record
name: Create a record
code: |
```ts
const { error } = await supabase
.from('countries')
.insert({ id: 1, name: 'Denmark' })
```
data:
sql: |
```sql
create table
countries (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: |
```ts
const { data, error } = await supabase
.from('countries')
.insert({ id: 1, name: 'Denmark' })
.select()
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
```
response: |
```json
{
"data": [
{
"id": 1,
"name": "Denmark"
}
],
"status": 201,
"statusText": "Created"
}
```
hideCodeBlock: true
- id: bulk-create
name: Bulk create
code: |
```ts
const { error } = await supabase
.from('countries')
.insert([
{ id: 1, name: 'Nepal' },
{ id: 1, name: 'Vietnam' },
])
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
```
response: |
```json
{
"error": {
"code": "23505",
"details": "Key (id)=(1) already exists.",
"hint": null,
"message": "duplicate key value violates unique constraint \"countries_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.
hideCodeBlock: true
- id: update
title: 'Modify data: update()'
$ref: '@supabase/postgrest-js.PostgrestQueryBuilder.update'
notes: |
- `update()` should always be combined with [Filters](/docs/reference/javascript/using-filters) to target the item(s) you wish to update.
examples:
- id: updating-your-data
name: Updating your data
code: |
```ts
const { error } = await supabase
.from('countries')
.update({ name: 'Australia' })
.eq('id', 1)
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
insert into
countries (id, name)
values
(1, 'Taiwan');
```
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: |
```ts
const { data, error } = await supabase
.from('countries')
.update({ name: 'Australia' })
.eq('id', 1)
.select()
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
insert into
countries (id, name)
values
(1, 'Taiwan');
```
response: |
```json
{
"data": [
{
"id": 1,
"name": "Australia"
}
],
"status": 200,
"statusText": "OK"
}
```
hideCodeBlock: true
- id: updating-json-data
name: Updating JSON data
code: |
```ts
const { data, error } = await supabase
.from('users')
.update({
address: {
street: 'Melrose Place',
postcode: 90210
}
})
.eq('address->postcode', 90210)
.select()
```
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()'
$ref: '@supabase/postgrest-js.PostgrestQueryBuilder.upsert'
notes: |
- Primary keys must be included in `values` to use upsert.
examples:
- id: upsert-your-data
name: Upsert your data
code: |
```ts
const { data, error } = await supabase
.from('countries')
.upsert({ id: 1, name: 'Albania' })
.select()
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
insert into
countries (id, name)
values
(1, 'Afghanistan');
```
response: |
```json
{
"data": [
{
"id": 1,
"name": "Albania"
}
],
"status": 201,
"statusText": "Created"
}
```
hideCodeBlock: true
isSpotlight: true
- id: bulk-upsert-your-data
name: Bulk Upsert your data
code: |
```ts
const { data, error } = await supabase
.from('countries')
.upsert([
{ id: 1, name: 'Albania' },
{ id: 2, name: 'Algeria' },
])
.select()
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
insert into
countries (id, name)
values
(1, 'Afghanistan');
```
response: |
```json
{
"data": [
{
"id": 1,
"name": "Albania"
},
{
"id": 2,
"name": "Algeria"
}
],
"status": 201,
"statusText": "Created"
}
```
hideCodeBlock: true
- id: upserting-into-tables-with-constraints
name: Upserting into tables with constraints
code: |
```ts
const { data, error } = await supabase
.from('users')
.upsert({ id: 42, handle: 'saoirse', display_name: 'Saoirse' }, { onConflict: 'handle' })
.select()
```
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 (id, handle, display_name)
values
(1, 'saoirse', null);
```
response: |
```json
{
"error": {
"code": "23505",
"details": "Key (handle)=(saoirse) already exists.",
"hint": null,
"message": "duplicate key value violates unique constraint \"users_handle_key\""
},
"status": 409,
"statusText": "Conflict"
}
```
description: |
In the following query, `upsert()` implicitly uses the `id`
(primary key) column to determine conflicts. If there is no existing
row with the same `id`, `upsert()` inserts a new row, which
will fail in this case as there is already a row with `handle` `"saoirse"`.
Using the `onConflict` option, you can instruct `upsert()` to use
another column with a unique constraint to determine conflicts.
hideCodeBlock: true
- id: delete
title: 'Delete data: delete()'
$ref: '@supabase/postgrest-js.PostgrestQueryBuilder.delete'
notes: |
- `delete()` should always be combined with [filters](/docs/reference/javascript/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.
examples:
- id: delete-records
name: Delete records
code: |
```ts
const { error } = await supabase
.from('countries')
.delete()
.eq('id', 1)
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
insert into
countries (id, name)
values
(1, 'Spain');
```
response: |
```json
{
"status": 204,
"statusText": "No Content"
}
```
hideCodeBlock: true
isSpotlight: 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.
```sql
create or replace function hello_world() returns text as $$
select 'Hello world';
$$ language sql;
```
$ref: '@supabase/postgrest-js.PostgrestClient.rpc'
examples:
- id: call-a-postgres-function-without-arguments
name: Call a Postgres function without arguments
code: |
```ts
const { data, error } = await supabase.rpc('hello_world')
```
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: |
```ts
const { data, error } = await supabase.rpc('echo', { say: '👋' })
```
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: |
```ts
const { data, error } = await supabase.rpc('add_one_each', { arr: [1, 2, 3] })
```
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: |
```ts
const { data, error } = await supabase
.rpc('list_stored_countries')
.eq('id', 1)
.single()
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
insert into
countries (id, name)
values
(1, 'France'),
(2, 'United Kingdom');
create function list_stored_countries() returns setof countries as $$
select * from countries;
$$ language sql;
```
response: |
```json
{
"data": {
"id": 1,
"name": "France"
},
"status": 200,
"statusText": "OK"
}
```
description: |
Postgres functions that return tables can also be combined with
[Filters](/docs/reference/javascript/using-filters) and
[Modifiers](/docs/reference/javascript/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()`, `upsert()`, and `delete()` queries.
If a Postgres function returns a table response, you can also apply filters.
examples:
- id: applying-filters
name: Applying Filters
description: |
Filters must be applied after any of `select()`, `update()`, `upsert()`,
`delete()`, and `rpc()` and before
[modifiers](/docs/reference/javascript/using-modifiers).
code: |
```ts
const { data, error } = await supabase
.from('cities')
.select('name, country_id')
.eq('name', 'The Shire') // Correct
const { data, error } = await supabase
.from('cities')
.eq('name', '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:
```ts
const { data, error } = await supabase
.from('cities')
.select('name, country_id')
.gte('population', 1000)
.lt('population', 10000)
```
code: |
```ts
const { data, error } = await supabase
.from('cities')
.select('name, country_id')
.gte('population', 1000)
.lt('population', 10000)
```
- id: conditional-chaining
name: Conditional Chaining
description: |
Filters can be built up one step at a time and then executed. For example:
```ts
const filterByName = null
const filterPopLow = 1000
const filterPopHigh = 10000
let query = supabase
.from('cities')
.select('name, country_id')
if (filterByName) { query = query.eq('name', filterByName) }
if (filterPopLow) { query = query.gte('population', filterPopLow) }
if (filterPopHigh) { query = query.lt('population', filterPopHigh) }
const { data, error } = await query
```
code: |
```ts
const filterByName = null
const filterPopLow = 1000
const filterPopHigh = 10000
let query = supabase
.from('cities')
.select('name, country_id')
if (filterByName) { query = query.eq('name', filterByName) }
if (filterPopLow) { query = query.gte('population', filterPopLow) }
if (filterPopHigh) { query = query.lt('population', filterPopHigh) }
const { data, error } = await query
```
- id: filter-by-value-within-json-column
name: Filter by values within a JSON column
code: |
```ts
const { data, error } = await supabase
.from('users')
.select()
.eq('address->postcode', 90210)
```
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: |
```ts
const { data, error } = await supabase
.from('countries')
.select(`
name,
cities!inner (
name
)
`)
.eq('cities.name', 'Bali')
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
create table
cities (
id int8 primary key,
country_id int8 not null references countries,
name text
);
insert into
countries (id, name)
values
(1, 'Germany'),
(2, 'Indonesia');
insert into
cities (id, country_id, name)
values
(1, 2, 'Bali'),
(2, 1, 'Munich');
```
response: |
```json
{
"data": [
{
"name": "Indonesia",
"cities": [
{
"name": "Bali"
}
]
}
],
"status": 200,
"statusText": "OK"
}
```
description: |
You can filter on foreign tables in your `select()` query using dot
notation.
######## TODO CHECK FILTER YAML ERRORS ########
- id: eq
title: eq()
$ref: '@supabase/postgrest-js.PostgrestFilterBuilder.eq'
examples:
- id: with-select
name: With `select()`
code: |
```ts
const { data, error } = await supabase
.from('countries')
.select()
.eq('name', 'Albania')
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
insert into
countries (id, name)
values
(1, 'Afghanistan'),
(2, 'Albania'),
(3, 'Algeria');
```
response: |
```json
{
"data": [
{
"id": 2,
"name": "Albania"
}
],
"status": 200,
"statusText": "OK"
}
```
hideCodeBlock: true
isSpotlight: true
- id: neq
title: neq()
$ref: '@supabase/postgrest-js.PostgrestFilterBuilder.neq'
examples:
- id: with-select
name: With `select()`
code: |
```ts
const { data, error } = await supabase
.from('countries')
.select()
.neq('name', 'Albania')
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
insert into
countries (id, name)
values
(1, 'Afghanistan'),
(2, 'Albania'),
(3, 'Algeria');
```
response: |
```json
{
"data": [
{
"id": 1,
"name": "Afghanistan"
},
{
"id": 3,
"name": "Algeria"
}
],
"status": 200,
"statusText": "OK"
}
```
hideCodeBlock: true
isSpotlight: true
- id: gt
title: gt()
$ref: '@supabase/postgrest-js.PostgrestFilterBuilder.gt'
examples:
- id: with-select
name: With `select()`
code: |
```ts
const { data, error } = await supabase
.from('countries')
.select()
.gt('id', 2)
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
insert into
countries (id, name)
values
(1, 'Afghanistan'),
(2, 'Albania'),
(3, 'Algeria');
```
response: |
```json
{
"data": [
{
"id": 3,
"name": "Algeria"
}
],
"status": 200,
"statusText": "OK"
}
```
hideCodeBlock: true
isSpotlight: true
- id: gte
title: gte()
$ref: '@supabase/postgrest-js.PostgrestFilterBuilder.gte'
examples:
- id: with-select
name: With `select()`
code: |
```ts
const { data, error } = await supabase
.from('countries')
.select()
.gte('id', 2)
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
insert into
countries (id, name)
values
(1, 'Afghanistan'),
(2, 'Albania'),
(3, 'Algeria');
```
response: |
```json
{
"data": [
{
"id": 2,
"name": "Albania"
},
{
"id": 3,
"name": "Algeria"
}
],
"status": 200,
"statusText": "OK"
}
```
hideCodeBlock: true
isSpotlight: true
- id: lt
title: lt()
$ref: '@supabase/postgrest-js.PostgrestFilterBuilder.lt'
examples:
- id: with-select
name: With `select()`
code: |
```ts
const { data, error } = await supabase
.from('countries')
.select()
.lt('id', 2)
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
insert into
countries (id, name)
values
(1, 'Afghanistan'),
(2, 'Albania'),
(3, 'Algeria');
```
response: |
```json
{
"data": [
{
"id": 1,
"name": "Afghanistan"
}
],
"status": 200,
"statusText": "OK"
}
```
hideCodeBlock: true
isSpotlight: true
- id: lte
title: lte()
$ref: '@supabase/postgrest-js.PostgrestFilterBuilder.lte'
examples:
- id: with-select
name: With `select()`
code: |
```ts
const { data, error } = await supabase
.from('countries')
.select()
.lte('id', 2)
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
insert into
countries (id, name)
values
(1, 'Afghanistan'),
(2, 'Albania'),
(3, 'Algeria');
```
response: |
```json
{
"data": [
{
"id": 1,
"name": "Afghanistan"
},
{
"id": 2,
"name": "Albania"
}
],
"status": 200,
"statusText": "OK"
}
```
hideCodeBlock: true
isSpotlight: true
- id: like
title: like()
$ref: '@supabase/postgrest-js.PostgrestFilterBuilder.like'
examples:
- id: with-select
name: With `select()`
code: |
```ts
const { data, error } = await supabase
.from('countries')
.select()
.like('name', '%Alba%')
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
insert into
countries (id, name)
values
(1, 'Afghanistan'),
(2, 'Albania'),
(3, 'Algeria');
```
response: |
hideCodeBlock: true
isSpotlight: true
- id: ilike
title: ilike()
$ref: '@supabase/postgrest-js.PostgrestFilterBuilder.ilike'
examples:
- id: with-select
name: With `select()`
code: |
```ts
const { data, error } = await supabase
.from('countries')
.select()
.ilike('name', '%alba%')
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
insert into
countries (id, name)
values
(1, 'Afghanistan'),
(2, 'Albania'),
(3, 'Algeria');
```
response: |
```json
{
"data": [
{
"id": 2,
"name": "Albania"
}
],
"status": 200,
"statusText": "OK"
}
```
hideCodeBlock: true
isSpotlight: true
- id: is
title: is()
$ref: '@supabase/postgrest-js.PostgrestFilterBuilder.is'
examples:
- id: checking-nullness
name: Checking for nullness, true or false
code: |
```ts
const { data, error } = await supabase
.from('countries')
.select()
.is('name', null)
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
insert into
countries (id, name)
values
(1, 'null'),
(2, null);
```
response: |
```json
{
"data": [
{
"id": 1,
"name": "null"
}
],
"status": 200,
"statusText": "OK"
}
```
description: |
Using the `eq()` filter doesn't work when filtering for `null`.
Instead, you need to use `is()`.
hideCodeBlock: true
isSpotlight: true
- id: in
title: in()
$ref: '@supabase/postgrest-js.PostgrestFilterBuilder.in'
examples:
- id: with-select
name: With `select()`
code: |
```ts
const { data, error } = await supabase
.from('countries')
.select()
.in('name', ['Albania', 'Algeria'])
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
insert into
countries (id, name)
values
(1, 'Afghanistan'),
(2, 'Albania'),
(3, 'Algeria');
```
response: |
```json
{
"data": [
{
"id": 2,
"name": "Albania"
},
{
"id": 3,
"name": "Algeria"
}
],
"status": 200,
"statusText": "OK"
}
```
hideCodeBlock: true
isSpotlight: true
- id: contains
title: contains()
$ref: '@supabase/postgrest-js.PostgrestFilterBuilder.contains'
examples:
- id: on-array-columns
name: On array columns
code: |
```ts
const { data, error } = await supabase
.from('users')
.select()
.contains('name', ['is:online', 'faction:red'])
```
data:
sql: |
```sql
create table
issues (
id int8 primary key,
title text,
tags text[]
);
insert into
issues (id, title, tags)
values
(1, 'Cache invalidation is not working', array['is:open', 'severity:high', 'priority:low']),
(2, 'Use better names', array['is:open', 'severity:low', 'priority:medium']);
```
response: |
```json
{
"data": [
{
"title": "Cache invalidation is not working"
}
],
"status": 200,
"statusText": "OK"
}
```
hideCodeBlock: true
isSpotlight: true
- id: on-range-columns
name: On range columns
code: |
```ts
const { data, error } = await supabase
.from('reservations')
.select()
.contains('during', '[2000-01-01 13:00, 2000-01-01 13:30)')
```
data:
sql: |
```sql
create table
reservations (
id int8 primary key,
room_name text,
during tsrange
);
insert into
reservations (id, room_name, during)
values
(1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),
(2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)');
```
response: |
```json
{
"data": [
{
"id": 1,
"room_name": "Emerald",
"during": "[\"2000-01-01 13:00:00\",\"2000-01-01 15:00:00\")"
}
],
"status": 200,
"statusText": "OK"
}
```
description: |
Postgres supports a number of [range
types](https://www.postgresql.org/docs/current/rangetypes.html). You
can filter on range columns using the string representation of range
values.
hideCodeBlock: true
- id: on-jsonb-columns
name: On `jsonb` columns
code: |
```ts
const { data, error } = await supabase
.from('users')
.select('name')
.contains('address', { postcode: 90210 })
```
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, "street": "Melrose Place" }'),
(2, 'Jane', '{}');
```
response: |
```json
{
"data": [
{
"name": "Michael"
}
],
"status": 200,
"statusText": "OK"
}
```
hideCodeBlock: true
- id: contained-by
title: containedBy()
$ref: '@supabase/postgrest-js.PostgrestFilterBuilder.containedBy'
examples:
- id: on-array-columns
name: On array columns
code: |
```ts
const { data, error } = await supabase
.from('classes')
.select('name')
.containedBy('days', ['monday', 'tuesday', 'wednesday', 'friday'])
```
data:
sql: |
```sql
create table
classes (
id int8 primary key,
name text,
days text[]
);
insert into
classes (id, name, days)
values
(1, 'Chemistry', array['monday', 'friday']),
(2, 'History', array['monday', 'wednesday', 'thursday']);
```
response: |
```json
{
"data": [
{
"name": "Chemistry"
}
],
"status": 200,
"statusText": "OK"
}
```
hideCodeBlock: true
isSpotlight: true
- id: on-range-columns
name: On range columns
code: |
```ts
const { data, error } = await supabase
.from('reservations')
.select()
.containedBy('during', '[2000-01-01 00:00, 2000-01-01 23:59)')
```
data:
sql: |
```sql
create table
reservations (
id int8 primary key,
room_name text,
during tsrange
);
insert into
reservations (id, room_name, during)
values
(1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),
(2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)');
```
response: |
```json
{
"data": [
{
"id": 1,
"room_name": "Emerald",
"during": "[\"2000-01-01 13:00:00\",\"2000-01-01 15:00:00\")"
}
],
"status": 200,
"statusText": "OK"
}
```
description: |
Postgres supports a number of [range
types](https://www.postgresql.org/docs/current/rangetypes.html). You
can filter on range columns using the string representation of range
values.
hideCodeBlock: true
- id: on-jsonb-columns
name: On `jsonb` columns
code: |
```ts
const { data, error } = await supabase
.from('users')
.select('name')
.containedBy('address', {})
```
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, "street": "Melrose Place" }'),
(2, 'Jane', '{}');
```
response: |
```json
{
"data": [
{
"name": "Jane"
}
],
"status": 200,
"statusText": "OK"
}
```
hideCodeBlock: true
- id: range-gt
title: rangeGt()
$ref: '@supabase/postgrest-js.PostgrestFilterBuilder.rangeGt'
examples:
- id: with-select
name: With `select()`
code: |
```ts
const { data, error } = await supabase
.from('reservations')
.select()
.rangeGt('during', '[2000-01-02 08:00, 2000-01-02 09:00)')
```
data:
sql: |
```sql
create table
reservations (
id int8 primary key,
room_name text,
during tsrange
);
insert into
reservations (id, room_name, during)
values
(1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),
(2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)');
```
response: |
```json
{
"data": [
{
"id": 2,
"room_name": "Topaz",
"during": "[\"2000-01-02 09:00:00\",\"2000-01-02 10:00:00\")"
}
],
"status": 200,
"statusText": "OK"
}
```
description: |
Postgres supports a number of [range
types](https://www.postgresql.org/docs/current/rangetypes.html). You
can filter on range columns using the string representation of range
values.
hideCodeBlock: true
isSpotlight: true
- id: range-gte
title: rangeGte()
$ref: '@supabase/postgrest-js.PostgrestFilterBuilder.rangeGte'
examples:
- id: with-select
name: With `select()`
code: |
```ts
const { data, error } = await supabase
.from('reservations')
.select()
.rangeGte('during', '[2000-01-02 08:30, 2000-01-02 09:30)')
```
data:
sql: |
```sql
create table
reservations (
id int8 primary key,
room_name text,
during tsrange
);
insert into
reservations (id, room_name, during)
values
(1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),
(2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)');
```
response: |
```json
{
"data": [
{
"id": 2,
"room_name": "Topaz",
"during": "[\"2000-01-02 09:00:00\",\"2000-01-02 10:00:00\")"
}
],
"status": 200,
"statusText": "OK"
}
```
description: |
Postgres supports a number of [range
types](https://www.postgresql.org/docs/current/rangetypes.html). You
can filter on range columns using the string representation of range
values.
hideCodeBlock: true
isSpotlight: true
- id: range-lt
title: rangeLt()
$ref: '@supabase/postgrest-js.PostgrestFilterBuilder.rangeLt'
examples:
- id: with-select
name: With `select()`
code: |
```ts
const { data, error } = await supabase
.from('reservations')
.select()
.rangeLt('during', '[2000-01-01 15:00, 2000-01-01 16:00)')
```
data:
sql: |
```sql
create table
reservations (
id int8 primary key,
room_name text,
during tsrange
);
insert into
reservations (id, room_name, during)
values
(1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),
(2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)');
```
response: |
```json
{
"data": [
{
"id": 1,
"room_name": "Emerald",
"during": "[\"2000-01-01 13:00:00\",\"2000-01-01 15:00:00\")"
}
],
"status": 200,
"statusText": "OK"
}
```
description: |
Postgres supports a number of [range
types](https://www.postgresql.org/docs/current/rangetypes.html). You
can filter on range columns using the string representation of range
values.
hideCodeBlock: true
isSpotlight: true
- id: range-lte
title: rangeLte()
$ref: '@supabase/postgrest-js.PostgrestFilterBuilder.rangeLte'
examples:
- id: with-select
name: With `select()`
code: |
```ts
const { data, error } = await supabase
.from('reservations')
.select()
.rangeLte('during', '[2000-01-01 14:00, 2000-01-01 16:00)')
```
data:
sql: |
```sql
create table
reservations (
id int8 primary key,
room_name text,
during tsrange
);
insert into
reservations (id, room_name, during)
values
(1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),
(2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)');
```
response: |
```json
{
"data": [
{
"id": 1,
"room_name": "Emerald",
"during": "[\"2000-01-01 13:00:00\",\"2000-01-01 15:00:00\")"
}
],
"status": 200,
"statusText": "OK"
}
```
description: |
Postgres supports a number of [range
types](https://www.postgresql.org/docs/current/rangetypes.html). You
can filter on range columns using the string representation of range
values.
hideCodeBlock: true
isSpotlight: true
- id: range-adjacent
title: rangeAdjacent()
$ref: '@supabase/postgrest-js.PostgrestFilterBuilder.rangeAdjacent'
examples:
- id: with-select
name: With `select()`
code: |
```ts
const { data, error } = await supabase
.from('reservations')
.select()
.rangeAdjacent('during', '[2000-01-01 12:00, 2000-01-01 13:00)')
```
data:
sql: |
```sql
create table
reservations (
id int8 primary key,
room_name text,
during tsrange
);
insert into
reservations (id, room_name, during)
values
(1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),
(2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)');
```
response: |
```json
{
"data": [
{
"id": 1,
"room_name": "Emerald",
"during": "[\"2000-01-01 13:00:00\",\"2000-01-01 15:00:00\")"
}
],
"status": 200,
"statusText": "OK"
}
```
description: |
Postgres supports a number of [range
types](https://www.postgresql.org/docs/current/rangetypes.html). You
can filter on range columns using the string representation of range
values.
hideCodeBlock: true
isSpotlight: true
- id: overlaps
title: overlaps()
$ref: '@supabase/postgrest-js.PostgrestFilterBuilder.overlaps'
examples:
- id: on-array-columns
name: On array columns
code: |
```ts
const { data, error } = await supabase
.from('issues')
.select('title')
.overlaps('tags', ['is:closed', 'severity:high'])
```
data:
sql: |
```sql
create table
issues (
id int8 primary key,
title text,
tags text[]
);
insert into
issues (id, title, tags)
values
(1, 'Cache invalidation is not working', array['is:open', 'severity:high', 'priority:low']),
(2, 'Use better names', array['is:open', 'severity:low', 'priority:medium']);
```
response: |
```json
{
"data": [
{
"title": "Cache invalidation is not working"
}
],
"status": 200,
"statusText": "OK"
}
```
hideCodeBlock: true
isSpotlight: true
- id: on-range-columns
name: On range columns
code: |
```ts
const { data, error } = await supabase
.from('reservations')
.select()
.overlaps('during', '[2000-01-01 12:45, 2000-01-01 13:15)')
```
data:
sql: |
```sql
create table
reservations (
id int8 primary key,
room_name text,
during tsrange
);
insert into
reservations (id, room_name, during)
values
(1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),
(2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)');
```
response: |
```json
{
"data": [
{
"id": 1,
"room_name": "Emerald",
"during": "[\"2000-01-01 13:00:00\",\"2000-01-01 15:00:00\")"
}
],
"status": 200,
"statusText": "OK"
}
```
description: |
Postgres supports a number of [range
types](https://www.postgresql.org/docs/current/rangetypes.html). You
can filter on range columns using the string representation of range
values.
hideCodeBlock: true
# TODO: schema & result
- id: text-search
title: textSearch()
$ref: '@supabase/postgrest-js.PostgrestFilterBuilder.textSearch'
notes: |
- For more information, see [Postgres full text search](/docs/guides/database/full-text-search).
examples:
- id: text-search
name: Text search
code: |
```ts
const { data, error } = await supabase
.from('quotes')
.select('catchphrase')
.textSearch('catchphrase', `'fat' & 'cat'`, {
config: 'english'
})
```
- id: basic-normalization
name: Basic normalization
description: Uses PostgreSQL's `plainto_tsquery` function.
code: |
```ts
const { data, error } = await supabase
.from('quotes')
.select('catchphrase')
.textSearch('catchphrase', `'fat' & 'cat'`, {
type: 'plain',
config: 'english'
})
```
- id: full-normalization
name: Full normalization
description: Uses PostgreSQL's `phraseto_tsquery` function.
code: |
```ts
const { data, error } = await supabase
.from('quotes')
.select('catchphrase')
.textSearch('catchphrase', `'fat' & 'cat'`, {
type: 'phrase',
config: 'english'
})
```
- id: web-search
name: Websearch
description: |
Uses PostgreSQL's `websearch_to_tsquery` function.
This function will never raise syntax errors, which makes it possible to use raw user-supplied input for search, and can be used
with advanced operators.
- `unquoted text`: text not inside quote marks will be converted to terms separated by & operators, as if processed by plainto_tsquery.
- `"quoted text"`: text inside quote marks will be converted to terms separated by <-> operators, as if processed by phraseto_tsquery.
- `OR`: the word “or” will be converted to the | operator.
- `-`: a dash will be converted to the ! operator.
code: |
```ts
const { data, error } = await supabase
.from('quotes')
.select('catchphrase')
.textSearch('catchphrase', `'fat or cat'`, {
type: 'websearch',
config: 'english'
})
```
- id: match
title: match()
$ref: '@supabase/postgrest-js.PostgrestFilterBuilder.match'
examples:
- id: with-select
name: With `select()`
code: |
```ts
const { data, error } = await supabase
.from('countries')
.select('name')
.match({ id: 2, name: 'Albania' })
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
insert into
countries (id, name)
values
(1, 'Afghanistan'),
(2, 'Albania'),
(3, 'Algeria');
```
response: |
```json
{
"data": [
{
"name": "Albania"
}
],
"status": 200,
"statusText": "OK"
}
```
hideCodeBlock: true
isSpotlight: true
- id: not
title: not()
$ref: '@supabase/postgrest-js.PostgrestFilterBuilder.not'
notes: |
not() expects you to use the raw PostgREST syntax for the filter values.
```ts
.not('id', 'in', '(5,6,7)') // Use `()` for `in` filter
.not('arraycol', 'cs', '{"a","b"}') // Use `cs` for `contains()`, `{}` for array values
```
examples:
- id: with-select
name: With `select()`
code: |
```ts
const { data, error } = await supabase
.from('countries')
.select()
.not('name', 'is', null)
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
insert into
countries (id, name)
values
(1, 'null'),
(2, null);
```
response: |
```json
{
"data": [
{
"id": 1,
"name": "null"
}
],
"status": 200,
"statusText": "OK"
}
```
hideCodeBlock: true
isSpotlight: true
- id: or
title: or()
$ref: '@supabase/postgrest-js.PostgrestFilterBuilder.or'
notes: |
or() expects you to use the raw PostgREST syntax for the filter names and values.
```ts
.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: |
```ts
const { data, error } = await supabase
.from('countries')
.select('name')
.or('id.eq.2,name.eq.Algeria')
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
insert into
countries (id, name)
values
(1, 'Afghanistan'),
(2, 'Albania'),
(3, 'Algeria');
```
response: |
```json
{
"data": [
{
"name": "Albania"
},
{
"name": "Algeria"
}
],
"status": 200,
"statusText": "OK"
}
```
hideCodeBlock: true
isSpotlight: true
- id: use-or-with-and
name: Use `or` with `and`
code: |
```ts
const { data, error } = await supabase
.from('countries')
.select('name')
.or('id.gt.3,and(id.eq.1,name.eq.Afghanistan)')
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
insert into
countries (id, name)
values
(1, 'Afghanistan'),
(2, 'Albania'),
(3, 'Algeria');
```
reponse: |
```json
{
"data": [
{
"name": "Afghanistan"
}
],
"status": 200,
"statusText": "OK"
}
```
hideCodeBlock: true
- id: use-or-on-foreign-tables
name: Use `or` on foreign tables
code: |
```ts
const { data, error } = await supabase
.from('countries')
.select(`
name,
cities!inner (
name
)
`)
.or('country_id.eq.1,name.eq.Beijing', { foreignTable: 'cities' })
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
create table
cities (
id int8 primary key,
country_id int8 not null references countries,
name text
);
insert into
countries (id, name)
values
(1, 'Germany'),
(2, 'Indonesia');
insert into
cities (id, country_id, name)
values
(1, 2, 'Bali'),
(2, 1, 'Munich');
```
response: |
```json
{
"data": [
{
"name": "Germany",
"cities": [
{
"name": "Munich"
}
]
}
],
"status": 200,
"statusText": "OK"
}
```
hideCodeBlock: true
- id: filter
title: filter()
$ref: '@supabase/postgrest-js.PostgrestFilterBuilder.filter'
notes: |
filter() expects you to use the raw PostgREST syntax for the filter values.
```ts
.filter('id', 'in', '(5,6,7)') // Use `()` for `in` filter
.filter('arraycol', 'cs', '{"a","b"}') // Use `cs` for `contains()`, `{}` for array values
```
examples:
- id: with-select
name: With `select()`
code: |
```ts
const { data, error } = await supabase
.from('countries')
.select()
.filter('name', 'in', '("Algeria","Japan")')
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
insert into
countries (id, name)
values
(1, 'Afghanistan'),
(2, 'Albania'),
(3, 'Algeria');
```
response: |
```json
{
"data": [
{
"id": 3,
"name": "Algeria"
}
],
"status": 200,
"statusText": "OK"
}
```
hideCodeBlock: true
isSpotlight: true
- id: on-a-foreign-table
name: On a foreign table
code: |
```ts
const { data, error } = await supabase
.from('countries')
.select(`
name,
cities!inner (
name
)
`)
.filter('cities.name', 'eq', 'Bali')
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
create table
cities (
id int8 primary key,
country_id int8 not null references countries,
name text
);
insert into
countries (id, name)
values
(1, 'Germany'),
(2, 'Indonesia');
insert into
cities (id, country_id, name)
values
(1, 2, 'Bali'),
(2, 1, 'Munich');
```
response: |
```json
{
"data": [
{
"name": "Indonesia",
"cities": [
{
"name": "Bali"
}
]
}
],
"status": 200,
"statusText": "OK"
}
```
hideCodeBlock: true
- id: using-modifiers
title: Using Modifiers
description: |
Filters work on the row level—they allows 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()
$ref: '@supabase/postgrest-js.PostgrestTransformBuilder.select'
examples:
- id: with-upsert
name: With `upsert()`
code: |
```ts
const { data, error } = await supabase
.from('countries')
.upsert({ id: 1, name: 'Algeria' })
.select()
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
insert into
countries (id, name)
values
(1, 'Afghanistan');
```
response: |
```json
{
"data": [
{
"id": 1,
"name": "Algeria"
}
],
"status": 201,
"statusText": "Created"
}
```
hideCodeBlock: true
isSpotlight: true
- id: order
title: order()
$ref: '@supabase/postgrest-js.PostgrestTransformBuilder.order'
examples:
- id: with-select
name: With `select()`
code: |
```ts
const { data, error } = await supabase
.from('countries')
.select('id', 'name')
.order('id', { ascending: false })
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
insert into
countries (id, name)
values
(1, 'Afghanistan'),
(2, 'Albania'),
(3, 'Algeria');
```
response: |
```json
{
"data": [
{
"id": 3,
"name": "Algeria"
},
{
"id": 2,
"name": "Albania"
},
{
"id": 1,
"name": "Afghanistan"
}
],
"status": 200,
"statusText": "OK"
}
```
hideCodeBlock: true
isSpotlight: true
- id: on-a-foreign-table
name: On a foreign table
code: |
```ts
const { data, error } = await supabase
.from('countries')
.select(`
name,
cities (
name
)
`)
.order('name', { foreignTable: 'cities', ascending: false })
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
create table
cities (
id int8 primary key,
country_id int8 not null references countries,
name text
);
insert into
countries (id, name)
values
(1, 'United States'),
(2, 'Vanuatu');
insert into
cities (id, country_id, name)
values
(1, 1, 'Atlanta'),
(2, 1, 'New York City');
```
response: |
```json
{
"data": [
{
"name": "United States",
"cities": [
{
"name": "New York City"
},
{
"name": "Atlanta"
}
]
},
{
"name": "Vanuatu",
"cities": []
}
],
"status": 200,
"statusText": "OK"
}
```
description: |
Ordering on foreign tables doesn't affect the ordering of
the parent table.
hideCodeBlock: true
- id: limit
title: limit()
$ref: '@supabase/postgrest-js.PostgrestTransformBuilder.limit'
examples:
- id: with-select
name: With `select()`
code: |
```ts
const { data, error } = await supabase
.from('countries')
.select('name')
.limit(1)
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
insert into
countries (id, name)
values
(1, 'Afghanistan'),
(2, 'Albania'),
(3, 'Algeria');
```
response: |
```json
{
"data": [
{
"name": "Afghanistan"
}
],
"status": 200,
"statusText": "OK"
}
```
hideCodeBlock: true
isSpotlight: true
- id: on-a-foreign-table
name: On a foreign table
code: |
```ts
const { data, error } = await supabase
.from('countries')
.select(`
name,
cities (
name
)
`)
.limit(1, { foreignTable: 'cities' })
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
create table
cities (
id int8 primary key,
country_id int8 not null references countries,
name text
);
insert into
countries (id, name)
values
(1, 'United States');
insert into
cities (id, country_id, name)
values
(1, 1, 'Atlanta'),
(2, 1, 'New York City');
```
response: |
```json
{
"data": [
{
"name": "United States",
"cities": [
{
"name": "Atlanta"
}
]
}
],
"status": 200,
"statusText": "OK"
}
```
hideCodeBlock: true
- id: range
title: range()
$ref: '@supabase/postgrest-js.PostgrestTransformBuilder.range'
examples:
- id: with-select
name: With `select()`
code: |
```ts
const { data, error } = await supabase
.from('countries')
.select('name')
.range(0, 1)
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
insert into
countries (id, name)
values
(1, 'Afghanistan'),
(2, 'Albania'),
(3, 'Algeria');
```
response: |
```json
{
"data": [
{
"name": "Afghanistan"
},
{
"name": "Albania"
}
],
"status": 200,
"statusText": "OK"
}
```
hideCodeBlock: true
isSpotlight: true
- id: abort-signal
$ref: '@supabase/postgrest-js.PostgrestTransformBuilder.abortSignal'
title: abortSignal()
examples:
- id: aborting-requests-in-flight
name: Aborting requests in-flight
code: |
```ts
const ac = new AbortController()
ac.abort()
const { data, error } = await supabase
.from('very_big_table')
.select()
.abortSignal(ac.signal)
```
data:
sql: |
```ts
const ac = new AbortController()
ac.abort()
const { data, error } = await supabase
.from('very_big_table')
.select()
.abortSignal(ac.signal)
```
response: |
```json
{
"error": {
"message": "FetchError: The user aborted a request.",
"details": "",
"hint": "",
"code": ""
},
"status": 400,
"statusText": "Bad Request"
}
```
description: |
You can use an [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) to abort requests.
Note that `status` and `statusText` don't mean anything for aborted requests as the request wasn't fulfilled.
hideCodeBlock: true
isSpotlight: true
- id: single
title: single()
$ref: '@supabase/postgrest-js.PostgrestTransformBuilder.single'
examples:
- id: with-select
name: With `select()`
code: |
```ts
const { data, error } = await supabase
.from('countries')
.select('name')
.limit(1)
.single()
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
insert into
countries (id, name)
values
(1, 'Afghanistan'),
(2, 'Albania'),
(3, 'Algeria');
```
response: |
```json
{
"data": {
"name": "Afghanistan"
},
"status": 200,
"statusText": "OK"
}
```
hideCodeBlock: true
isSpotlight: true
- id: maybe-single
title: maybeSingle()
$ref: '@supabase/postgrest-js.PostgrestTransformBuilder.maybeSingle'
examples:
- id: with-select
name: With `select()`
code: |
```ts
const { data, error } = await supabase
.from('countries')
.select()
.eq('name', 'Singapore')
.maybeSingle()
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
insert into
countries (id, name)
values
(1, 'Afghanistan'),
(2, 'Albania'),
(3, 'Algeria');
```
response: |
```json
{
"status": 200,
"statusText": "OK"
}
```
hideCodeBlock: true
isSpotlight: true
- id: csv
$ref: '@supabase/postgrest-js.PostgrestTransformBuilder.csv'
title: csv()
examples:
- id: return-data-as-csv
name: Return data as CSV
code: |
```ts
const { data, error } = await supabase
.from('countries')
.select()
.csv()
```
data:
sql: |
```sql
create table
countries (id int8 primary key, name text);
insert into
countries (id, name)
values
(1, 'Afghanistan'),
(2, 'Albania'),
(3, 'Algeria');
```
response: |
```json
{
"data": "id,name\n1,Afghanistan\n2,Albania\n3,Algeria",
"status": 200,
"statusText": "OK"
}
```
description: |
By default, the data is returned in JSON format, but can also be returned as Comma Separated Values.
hideCodeBlock: true
isSpotlight: true
- id: returns
$ref: '@supabase/postgrest-js.PostgrestTransformBuilder.returns'
title: returns()
examples:
- id: override-type-of-successful-response
name: Override type of successful response
code: |
```ts
const { data } = await supabase
.from('countries')
.select()
.returns<MyType>()
```
response: |
```
let x: typeof data // MyType | null
```
hideCodeBlock: true
isSpotlight: true
# NOTE: Not available on currently deployed PostgREST
# db.geojson():
# $ref: '@supabase/postgrest-js.PostgrestTransformBuilder.geojson'
# title: geojson()
# NOTE: Not available on currently deployed PostgREST
# db.explain():
# $ref: '@supabase/postgrest-js.PostgrestTransformBuilder.explain'
# title: explain()
# NOTE: Not available on currently deployed PostgREST
# db.rollback():
# $ref: '@supabase/postgrest-js.PostgrestTransformBuilder.rollback'
# title: rollback()
# examples:
# - id: With `delete()`
# description: |
# <details>
# <summary>Schema</summary>
# ```sql
# create table
# countries (id int8 primary key, name text);
# insert into
# countries (id, name)
# values
# (1, 'Spain');
# ```
# </details>
# ```ts
# const { error } = await supabase
# .from('countries')
# .delete()
# .eq('id', 1)
# .rollback()
# ```
# <details>
# <summary>Result</summary>
# ```json
# {
# "status": 204,
# "statusText": "No Content"
# }
# ```
# </details>
# ```ts
# const { data, error } = await supabase
# .from('countries')
# .select()
# ```
# <details>
# <summary>Result</summary>
# ```json
# {
# "data": [
# {
# "id": 1,
# "name": "Spain"
# }
# ],
# "status": 200,
# "statusText": "OK"
# }
# ```
# </details>
# hideCodeBlock: true
# isSpotlight: true
# js: |
# ```ts
# const { error } = await supabase
# .from('countries')
# .delete()
# .eq('id', 1)
# ```
- id: invoke
title: invoke()
description: |
Invoke a Supabase Function.
$ref: '@supabase/functions-js.FunctionsClient.invoke'
notes: |
- Requires an Authorization header.
- Invoke params generally match the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) spec.
- When you pass in a body to your function, we automatically attach the Content-Type header for `Blob`, `ArrayBuffer`, `File`, `FormData` and `String`. If it doesn't match any of these types we assume the payload is `json`, serialise it and attach the `Content-Type` header as `application/json`. You can override this behaviour by passing in a `Content-Type` header of your own.
- Responses are automatically parsed as `json`, `blob` and `form-data` depending on the `Content-Type` header sent by your function. Responses are parsed as `text` by default.
examples:
- id: basic-invocation
name: Basic invocation
isSpotlight: true
code: |
```js
const { data, error } = await supabase.functions.invoke('hello', {
body: { foo: 'bar' }
})
```
- id: error-handling
name: Error handling
description: |
A `FunctionsHttpError` error is returned if your function throws an error, `FunctionsRelayError` if the Supabase Relay has an error processing your function and `FunctionsFetchError` if there is a network error in calling your function.
isSpotlight: true
code: |
```js
import { FunctionsHttpError, FunctionsRelayError, FunctionsFetchError } from "@supabase/supabase-js";
const { data, error } = await supabase.functions.invoke('hello', {
headers: {
"my-custom-header": 'my-custom-header-value'
},
body: { foo: 'bar' }
})
if (error instanceof FunctionsHttpError) {
console.log('Function returned an error', error.message)
} else if (error instanceof FunctionsRelayError) {
console.log('Relay error:', error.message)
} else if (error instanceof FunctionsFetchError) {
console.log('Fetch error:', error.message)
}
```
- id: passing-custom-headers
name: Passing custom headers
description: |
You can pass custom headers to your function. Note: supabase-js automatically passes the `Authorization` header with the signed in user's JWT.
isSpotlight: true
code: |
```js
const { data, error } = await supabase.functions.invoke('hello', {
headers: {
"my-custom-header": 'my-custom-header-value'
},
body: { foo: 'bar' }
})
```
- id: subscribe
title: on().subscribe()
$ref: '@supabase/realtime-js.RealtimeChannel.on'
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/database/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.
examples:
- id: listen-to-broadcast
name: Listen to broadcast messages
isSpotlight: true
code: |
```js
supabase
.channel('any')
.on('broadcast', { event: 'cursor-pos' }, payload => {
console.log('Cursor position received!', payload)
})
.subscribe((status) => {
if (status === 'SUBSCRIBED') {
channel.send({
type: 'broadcast',
event: 'cursor-pos',
payload: { x: Math.random(), y: Math.random() },
})
}
})
```
- id: listen-to-presence-sync
name: Listen to presence sync
isSpotlight: true
code: |
```js
const channel = supabase.channel('any')
channel
.on('presence', { event: 'sync' }, () => {
console.log('Synced presence state: ', channel.presenceState())
})
.subscribe(async (status) => {
if (status === 'SUBSCRIBED') {
await channel.track({ online_at: new Date().toISOString() })
}
})
```
- id: listen-to-presence-join
name: Listen to presence join
isSpotlight: true
code: |
```js
const channel = supabase.channel('any')
channel
.on('presence', { event: 'join' }, ({ newPresences }) => {
console.log('Newly joined presences: ', newPresences)
})
.subscribe(async (status) => {
if (status === 'SUBSCRIBED') {
await channel.track({ online_at: new Date().toISOString() })
}
})
```
- id: listen-to-presence-leave
name: Listen to presence leave
isSpotlight: true
code: |
```js
const channel = supabase.channel('any')
channel
.on('presence', { event: 'leave' }, ({ leftPresences }) => {
console.log('Newly left presences: ', leftPresences)
})
.subscribe(async (status) => {
if (status === 'SUBSCRIBED') {
await channel.track({ online_at: new Date().toISOString() })
await channel.untrack()
}
})
```
- id: listen-to-all-database-changes
name: Listen to all database changes
isSpotlight: true
code: |
```js
supabase
.channel('any')
.on('postgres_changes', { event: '*', schema: '*' }, payload => {
console.log('Change received!', payload)
})
.subscribe()
```
- id: listen-to-a-specific-table
name: Listen to a specific table
code: |
```js
supabase
.channel('any')
.on('postgres_changes', { event: '*', schema: 'public', table: 'countries' }, payload => {
console.log('Change received!', payload)
})
.subscribe()
```
- id: listen-to-inserts
name: Listen to inserts
code: |
```js
supabase
.channel('any')
.on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'countries' }, payload => {
console.log('Change received!', payload)
})
.subscribe()
```
- 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: |
```js
supabase
.channel('any')
.on('postgres_changes', { event: 'UPDATE', schema: 'public', table: 'countries' }, payload => {
console.log('Change received!', payload)
})
.subscribe()
```
- 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 too:
```sql
alter table "your_table" replica identity full;
```
code: |
```js
supabase
.channel('any')
.on('postgres_changes', { event: 'DELETE', schema: 'public', table: 'countries' }, payload => {
console.log('Change received!', payload)
})
.subscribe()
```
- id: listen-to-multiple-events
name: Listen to multiple events
description: You can chain listeners if you want to listen to multiple events for each table.
code: |
```js
supabase
.channel('any')
.on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'countries' }, handleRecordInserted)
.on('postgres_changes', { event: 'DELETE', schema: 'public', table: 'countries' }, handleRecordDeleted)
.subscribe()
```
- id: listening-to-row-level-changes
name: Listen to row level changes
description: You can listen to individual rows using the format `{table}:{col}=eq.{val}` - where `{col}` is the column name, and `{val}` is the value which you want to match.
notes: |
- ``eq`` filter works with all database types as under the hood, it's casting both the filter value and the database value to the correct type and then comparing them.
code: |
```js
supabase
.channel('any')
.on('postgres_changes', { event: 'UPDATE', schema: 'public', table: 'countries', filter: 'id=eq.200' }, handleRecordUpdated)
.subscribe()
```
- id: get-channels
title: getChannels()
$ref: '@supabase/supabase-js.index.SupabaseClient.getChannels'
examples:
- id: get-all-channels
name: Get all channels
isSpotlight: true
code: |
```js
const channels = supabase.getChannels()
```
- id: remove-channel
title: removeChannel()
$ref: '@supabase/supabase-js.index.SupabaseClient.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.
examples:
- id: removes-a-channel
name: Removes a channel
isSpotlight: true
code: |
```js
supabase.removeChannel(myChannel)
```
- id: remove-all-channels
title: removeAllChannels()
$ref: '@supabase/supabase-js.index.SupabaseClient.removeAllChannels'
notes: |
- 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.
examples:
- id: remove-all-channels
name: Remove all channels
isSpotlight: true
code: |
```js
supabase.removeAllChannels()
```
- id: list-buckets
title: listBuckets()
$ref: '@supabase/storage-js.packages/StorageBucketApi.default.listBuckets'
notes: |
- RLS policy permissions required:
- `buckets` table permissions: `select`
- `objects` table permissions: none
- Refer to the [Storage guide](/docs/guides/storage#access-control) on how access control works
examples:
- id: list-buckets
name: List buckets
isSpotlight: true
code: |
```ts
const { data, error } = await supabase
.storage
.listBuckets()
```
- id: get-bucket
title: getBucket()
$ref: '@supabase/storage-js.packages/StorageBucketApi.default.getBucket'
notes: |
- RLS policy permissions required:
- `buckets` table permissions: `select`
- `objects` table permissions: none
- Refer to the [Storage guide](/docs/guides/storage#access-control) on how access control works
examples:
- id: get-bucket
name: Get bucket
isSpotlight: true
code: |
```js
const { data, error } = await supabase
.storage
.getBucket('avatars')
```
- id: create-bucket
title: createBucket()
$ref: '@supabase/storage-js.packages/StorageBucketApi.default.createBucket'
notes: |
- RLS policy permissions required:
- `buckets` table permissions: `insert`
- `objects` table permissions: none
- Refer to the [Storage guide](/docs/guides/storage#access-control) on how access control works
examples:
- id: create-bucket
name: Create bucket
isSpotlight: true
code: |
```js
const { data, error } = await supabase
.storage
.createBucket('avatars', { public: false })
```
- id: empty-bucket
title: emptyBucket()
$ref: '@supabase/storage-js.packages/StorageBucketApi.default.emptyBucket'
notes: |
- RLS policy permissions required:
- `buckets` table permissions: `select`
- `objects` table permissions: `select` and `delete`
- Refer to the [Storage guide](/docs/guides/storage#access-control) on how access control works
examples:
- id: empty-bucket
name: Empty bucket
isSpotlight: true
code: |
```js
const { data, error } = await supabase
.storage
.emptyBucket('avatars')
```
- id: update-bucket
title: updateBucket()
$ref: '@supabase/storage-js.packages/StorageBucketApi.default.updateBucket'
notes: |
- RLS policy permissions required:
- `buckets` table permissions: `update`
- `objects` table permissions: none
- Refer to the [Storage guide](/docs/guides/storage#access-control) on how access control works
examples:
- id: update-bucket
name: Update bucket
isSpotlight: true
code: |
```js
const { data, error } = await supabase
.storage
.updateBucket('avatars', { public: false })
```
- id: delete-bucket
title: deleteBucket()
$ref: '@supabase/storage-js.packages/StorageBucketApi.default.deleteBucket'
notes: |
- RLS policy permissions required:
- `buckets` table permissions: `select` and `delete`
- `objects` table permissions: none
- Refer to the [Storage guide](/docs/guides/storage#access-control) on how access control works
examples:
- id: delete-bucket
name: Delete bucket
isSpotlight: true
code: |
```js
const { data, error } = await supabase
.storage
.deleteBucket('avatars')
```
- id: from-upload
title: from.upload()
$ref: '@supabase/storage-js.packages/StorageFileApi.default.upload'
notes: |
- RLS policy permissions required:
- `buckets` table permissions: none
- `objects` table permissions: `insert`
- Refer to the [Storage guide](/docs/guides/storage#access-control) on how access control works
- For React Native, using either `Blob`, `File` or `FormData` does not work as intended. Upload file using `ArrayBuffer` from base64 file data instead, see example below.
examples:
- id: upload-file
name: Upload file
isSpotlight: true
code: |
```js
const avatarFile = event.target.files[0]
const { data, error } = await supabase
.storage
.from('avatars')
.upload('public/avatar1.png', avatarFile, {
cacheControl: '3600',
upsert: false
})
```
- id: upload-file-using-arraybuffer-from-base64-file-data
name: Upload file using `ArrayBuffer` from base64 file data
code: |
```js
import { decode } from 'base64-arraybuffer'
const { data, error } = await supabase
.storage
.from('avatars')
.upload('public/avatar1.png', decode('base64FileData'), {
contentType: 'image/png'
})
```
- id: from-update
title: from.update()
$ref: '@supabase/storage-js.packages/StorageFileApi.default.update'
notes: |
- RLS policy permissions required:
- `buckets` table permissions: none
- `objects` table permissions: `update` and `select`
- Refer to the [Storage guide](/docs/guides/storage#access-control) on how access control works
- For React Native, using either `Blob`, `File` or `FormData` does not work as intended. Update file using `ArrayBuffer` from base64 file data instead, see example below.
examples:
- id: update-file
name: Update file
isSpotlight: true
code: |
```js
const avatarFile = event.target.files[0]
const { data, error } = await supabase
.storage
.from('avatars')
.update('public/avatar1.png', avatarFile, {
cacheControl: '3600',
// Overwrite file if it exists
upsert: true
})
```
- id: update-file-using-arraybuffer-from-base64-file-data
name: Update file using `ArrayBuffer` from base64 file data
code: |
```js
import {decode} from 'base64-arraybuffer'
const { data, error } = await supabase
.storage
.from('avatars')
.update('public/avatar1.png', decode('base64FileData'), {
contentType: 'image/png'
})
```
- id: from-move
title: from.move()
$ref: '@supabase/storage-js.packages/StorageFileApi.default.move'
notes: |
- RLS policy permissions required:
- `buckets` table permissions: none
- `objects` table permissions: `update` and `select`
- Refer to the [Storage guide](/docs/guides/storage#access-control) on how access control works
examples:
- id: move-file
name: Move file
isSpotlight: true
code: |
```js
const { data, error } = await supabase
.storage
.from('avatars')
.move('public/avatar1.png', 'private/avatar2.png')
```
- id: from-copy
title: from.copy()
$ref: '@supabase/storage-js.packages/StorageFileApi.default.copy'
notes: |
- RLS policy permissions required:
- `buckets` table permissions: none
- `objects` table permissions: `insert` and `select`
- Refer to the [Storage guide](/docs/guides/storage#access-control) on how access control works
examples:
- id: copy-file
name: Copy file
isSpotlight: true
code: |
```js
const { data, error } = await supabase
.storage
.from('avatars')
.copy('public/avatar1.png', 'private/avatar2.png')
```
- id: from-create-signed-url
title: from.createSignedUrl()
$ref: '@supabase/storage-js.packages/StorageFileApi.default.createSignedUrl'
notes: |
- RLS policy permissions required:
- `buckets` table permissions: none
- `objects` table permissions: `select`
- Refer to the [Storage guide](/docs/guides/storage#access-control) on how access control works
examples:
- id: create-signed-url
name: Create Signed URL
isSpotlight: true
code: |
```js
const { data, error } = await supabase
.storage
.from('avatars')
.createSignedUrl('folder/avatar1.png', 60)
```
- id: create-signed-url-with-transformations
name: Create a signed URL for an asset with transformations
isSpotlight: true
code: |
```js
const { data } = supabase
.storage
.from('avatars')
.createSignedUrl('folder/avatar1.png', 60, {
transform: {
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: |
```js
const { data } = supabase
.storage
.from('avatars')
.createSignedUrl('folder/avatar1.png', 60, {
download: true,
})
```
- id: from-create-signed-urls
title: from.createSignedUrls()
$ref: '@supabase/storage-js.packages/StorageFileApi.default.createSignedUrls'
notes: |
- RLS policy permissions required:
- `buckets` table permissions: none
- `objects` table permissions: `select`
- Refer to the [Storage guide](/docs/guides/storage#access-control) on how access control works
examples:
- id: create-signed-urls
name: Create Signed URLs
isSpotlight: true
code: |
```js
const { data, error } = await supabase
.storage
.from('avatars')
.createSignedUrls(['folder/avatar1.png', 'folder/avatar2.png'], 60)
```
- id: from-get-public-url
title: from.getPublicUrl()
$ref: '@supabase/storage-js.packages/StorageFileApi.default.getPublicUrl'
notes: |
- The bucket needs to be set to public, either via [updateBucket()](/docs/reference/javascript/storage-updatebucket) or by going to Storage on [app.supabase.com](https://app.supabase.com), 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#access-control) on how access control works
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: |
```js
const { data } = supabase
.storage
.from('public-bucket')
.getPublicUrl('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: |
```js
const { data } = supabase
.storage
.from('public-bucket')
.getPublicUrl('folder/avatar1.png', {
transform: {
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: |
```js
const { data } = supabase
.storage
.from('public-bucket')
.getPublicUrl('folder/avatar1.png', {
download: true,
})
```
- id: from-download
title: from.download()
$ref: '@supabase/storage-js.packages/StorageFileApi.default.download'
notes: |
- RLS policy permissions required:
- `buckets` table permissions: none
- `objects` table permissions: `select`
- Refer to the [Storage guide](/docs/guides/storage#access-control) on how access control works
examples:
- id: download-file
name: Download file
isSpotlight: true
code: |
```js
const { data, error } = await supabase
.storage
.from('avatars')
.download('folder/avatar1.png')
```
- id: download-file-with-transformations
name: Download file with transformations
isSpotlight: true
code: |
```js
const { data, error } = await supabase
.storage
.from('avatars')
.download('folder/avatar1.png', {
transform: {
width: 100,
height: 100,
}
})
```
- id: from-remove
title: from.remove()
$ref: '@supabase/storage-js.packages/StorageFileApi.default.remove'
notes: |
- RLS policy permissions required:
- `buckets` table permissions: none
- `objects` table permissions: `delete` and `select`
- Refer to the [Storage guide](/docs/guides/storage#access-control) on how access control works
examples:
- id: delete-file
name: Delete file
isSpotlight: true
code: |
```js
const { data, error } = await supabase
.storage
.from('avatars')
.remove(['folder/avatar1.png'])
```
- id: from-list
title: from.list()
$ref: '@supabase/storage-js.packages/StorageFileApi.default.list'
notes: |
- RLS policy permissions required:
- `buckets` table permissions: none
- `objects` table permissions: `select`
- Refer to the [Storage guide](/docs/guides/storage#access-control) on how access control works
examples:
- id: list-files-in-a-bucket
name: List files in a bucket
isSpotlight: true
code: |
```js
const { data, error } = await supabase
.storage
.from('avatars')
.list('folder', {
limit: 100,
offset: 0,
sortBy: { column: 'name', order: 'asc' },
})
```
- id: search-files-in-a-bucket
name: Search files in a bucket
code: |
```js
const { data, error } = await supabase
.storage
.from('avatars')
.list('folder', {
limit: 100,
offset: 0,
sortBy: { column: 'name', order: 'asc' },
search: 'jon'
})
```