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.
Parameters
supabaseUrl
REQUIRED
string
The unique Supabase URL which is supplied when you create a new project in your project dashboard.
supabaseKey
REQUIRED
string
The unique Supabase Key which is supplied when you create a new project in your project dashboard.
options
Optional
SupabaseClientOptions
auth
Optional
object
autoRefreshToken
Optional
boolean
Automatically refreshes the token for logged-in users. Defaults to true.
debug
Optional
object
If debug messages for authentication client are emitted. Can be used to inspect the behavior of the library.
detectSessionInUrl
Optional
boolean
Detect a session from the URL. Used for OAuth login callbacks. Defaults to true.
flowType
Optional
object
OAuth flow to use - defaults to implicit flow. PKCE is recommended for mobile and server-side applications.
lock
Optional
object
Provide your own locking mechanism based on the environment. By default no locking is done at this time.
persistSession
Optional
boolean
Whether to persist a logged-in session to storage. Defaults to true.
storage
Optional
object
A storage provider. Used to store the logged-in session.
storageKey
Optional
string
Optional key name used for storing tokens in local storage.
db
Optional
object
The Postgres schema which your tables belong to. Must be on the list of exposed schemas in Supabase. Defaults to `public`.
schema
Optional
SchemaName
global
Optional
object
fetch
Optional
Fetch
A custom `fetch` implementation.
headers
Optional
Record
Optional headers for initializing the client.
realtime
Optional
RealtimeClientOptions
Options passed to the realtime-js instance
import { createClient } from'@supabase/supabase-js'// Create a single supabase client for interacting with your databaseconst supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key')
Fetch data
Perform a SELECT query on the table or view.
By default, Supabase projects return a maximum of 1,000 rows. This setting can be changed in your project's API settings. It's recommended that you keep it low to limit the payload size of accidental or malicious requests. You can use range() queries to paginate through your data.
The columns to retrieve, separated by commas. Columns can be renamed when returned with `customName:columnName`
options
Optional
object
Named parameters
count
Optional
"exact" | "planned" | "estimated"
Count algorithm to use to count rows in the table or view.
`"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the
hood.
`"planned"`: Approximated but fast count algorithm. Uses the Postgres
statistics under the hood.
`"estimated"`: Uses exact count for low numbers and planned count for high
numbers.
head
Optional
boolean
When set to `true`, `data` will not be returned.
Useful if you only need the count.
The values to insert. Pass an object to insert a single row
or an array to insert multiple rows.
options
Optional
object
Named parameters
count
Optional
"exact" | "planned" | "estimated"
Count algorithm to use to count inserted rows.
`"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the
hood.
`"planned"`: Approximated but fast count algorithm. Uses the Postgres
statistics under the hood.
`"estimated"`: Uses exact count for low numbers and planned count for high
numbers.
defaultToNull
Optional
boolean
Make missing fields default to `null`.
Otherwise, use the default value for the column. Only applies for bulk
inserts.
update() should always be combined with Filters to target the item(s) you wish to update.
Parameters
values
REQUIRED
Row
The values to update with
options
Optional
object
Named parameters
count
Optional
"exact" | "planned" | "estimated"
Count algorithm to use to count updated rows.
`"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the
hood.
`"planned"`: Approximated but fast count algorithm. Uses the Postgres
statistics under the hood.
`"estimated"`: Uses exact count for low numbers and planned count for high
numbers.
Perform an UPSERT on the table or view. Depending on the column(s) passed
to onConflict, .upsert() allows you to perform the equivalent of
.insert() if a row with the corresponding onConflict columns doesn't
exist, or if it does exist, perform an alternative action depending on
ignoreDuplicates.
Primary keys must be included in values to use upsert.
Parameters
values
REQUIRED
object[]
The values to upsert with. Pass an object to upsert a
single row or an array to upsert multiple rows.
options
Optional
object
Named parameters
count
Optional
"exact" | "planned" | "estimated"
Count algorithm to use to count upserted rows.
`"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the
hood.
`"planned"`: Approximated but fast count algorithm. Uses the Postgres
statistics under the hood.
`"estimated"`: Uses exact count for low numbers and planned count for high
numbers.
defaultToNull
Optional
boolean
Make missing fields default to `null`.
Otherwise, use the default value for the column. This only applies when
inserting new rows, not when merging with existing rows under
`ignoreDuplicates: false`. This also only applies when doing bulk upserts.
ignoreDuplicates
Optional
boolean
If `true`, duplicate rows are ignored. If
`false`, duplicate rows are merged with existing rows.
onConflict
Optional
string
Comma-separated UNIQUE column(s) to specify how
duplicate rows are determined. Two rows are duplicates if all the
`onConflict` columns are equal.
delete() should always be combined with filters to target the item(s) you wish to delete.
If you use delete() with filters and you have
RLS enabled, only
rows visible through SELECT policies are deleted. Note that by default
no rows are visible, so you need at least one SELECT/ALL policy that
makes the rows visible.
Parameters
options
Optional
object
Named parameters
count
Optional
"exact" | "planned" | "estimated"
Count algorithm to use to count deleted rows.
`"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the
hood.
`"planned"`: Approximated but fast count algorithm. Uses the Postgres
statistics under the hood.
`"estimated"`: Uses exact count for low numbers and planned count for high
numbers.
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.
create or replace function hello_world() returns text as $$
select 'Hello world';
$$ language sql;
Parameters
fn
REQUIRED
FunctionName
The function name to call
args
Optional
object
The arguments to pass to the function call
options
Optional
object
Named parameters
count
Optional
"exact" | "planned" | "estimated"
Count algorithm to use to count rows returned by the
function. Only applicable for [set-returning
functions](https://www.postgresql.org/docs/current/functions-srf.html).
`"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the
hood.
`"planned"`: Approximated but fast count algorithm. Uses the Postgres
statistics under the hood.
`"estimated"`: Uses exact count for low numbers and planned count for high
numbers.
head
Optional
boolean
When set to `true`, `data` will not be returned.
Useful if you only need the count.
Match only rows which satisfy at least one of the filters.
or() expects you to use the raw PostgREST syntax for the filter names and values.
1.or('id.in.(5,6,7), arraycol.cs.{"a","b"}') // Use `()` for `in` filter, `{}` for array values and `cs` for `contains()`.2.or('id.in.(5,6,7), arraycol.cd.{"a","b"}') // Use `cd` for `containedBy()`
Parameters
filters
REQUIRED
string
The filters to use, following PostgREST syntax
options
Optional
object
Named parameters
foreignTable
Optional
string
Deprecated, use `referencedTable` instead
referencedTable
Optional
string
Set this to filter on referenced tables
instead of the parent table
Filters work on the row level—they allow you to return rows that
only match certain conditions without changing the shape of the rows.
Modifiers are everything that don't fit that definition—allowing you to
change the format of the response (e.g., returning a CSV string).
Modifiers must be specified after filters. Some modifiers only apply for
queries that return rows (e.g., select() or rpc() on a function that
returns a table response).
Limit the query result by starting at an offset (from) and ending at the offset (from + to).
Only records within this range are returned.
This respects the query order and if there is no order clause the range could behave unexpectedly.
The from and to values are 0-based and inclusive: range(1, 3) will include the second, third
and fourth rows of the query.
Parameters
from
REQUIRED
number
The starting index from which to limit the result
to
REQUIRED
number
The last index to which to limit the result
options
Optional
object
Named parameters
foreignTable
Optional
string
Deprecated, use `options.referencedTable`
instead
referencedTable
Optional
string
Set this to limit rows of referenced
tables instead of the parent table
const { data } = await supabase
.from('countries')
.select()
.returns<MyType>()
Using explain
Return data as the EXPLAIN plan for the query.
For debugging slow queries, you can get the Postgres EXPLAIN execution plan of a query
using the explain() method. This works on any query, even for rpc() or writes.
Explain is not enabled by default as it can reveal sensitive information about your database.
It's best to only enable this for testing environments but if you wish to enable it for production you can provide additional protection by using a pre-request function.
The auth methods can be accessed via the supabase.auth namespace.
By default, the supabase client sets persistSession to true and attempts to store the session in local storage. When using the supabase client in an environment that doesn't support local storage, you might notice the following warning message being logged:
No storage option exists to persist the session, which may result in unexpected behavior when using auth.
If you want to set persistSession to true, please provide a storage option or you may set persistSession to false to disable this warning.
This warning message can be safely ignored if you're not using auth on the server-side. If you are using auth and you want to set persistSession to true, you will need to provide a custom storage implementation that follows this interface.
Any email links and one-time passwords (OTPs) sent have a default expiry of 24 hours. We have the following rate limits in place to guard against brute force attacks.
The expiry of an access token can be set in the "JWT expiry limit" field in your project's auth settings. A refresh token never expires and can only be used once.
By default, the user needs to verify their email address before logging in. To turn this off, disable Confirm email in your project.
Confirm email determines if users need to confirm their email address after signing up.
If Confirm email is enabled, 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 by default. You can modify your SITE_URL or add additional redirect URLs in your project.
If signUp() is called for an existing confirmed user:
If Confirm email is enabled in your project, 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().
Allows signing in with an OIDC ID token. The authentication provider used
should be enabled and configured.
Parameters
credentials
REQUIRED
SignInWithIdTokenCredentials
token
REQUIRED
string
OIDC ID token issued by the specified provider. The `iss` claim in the ID token must match the supplied provider. Some ID tokens contain an `at_hash` which require that you provide an `access_token` value to be accepted properly. If the token contains a `nonce` claim you must supply the nonce used to obtain the ID token.
Provider name or OIDC `iss` value identifying which provider should be used to verify the provided token. Supported names: `google`, `apple`, `azure`, `facebook`, `keycloak` (deprecated).
access_token
Optional
string
If the ID token contains an `at_hash` claim, then the hash of this value is compared to the value in the ID token.
nonce
Optional
string
If the ID token contains a `nonce` claim, then the hash of this value is compared to the value in the ID token.
options
Optional
object
captchaToken
Optional
string
Verification token received when the user completes the captcha on the site.
Log in a user using magiclink or a one-time password (OTP).
Requires either an email or phone number.
This method is used for passwordless sign-ins where a OTP is sent to the user's email or phone number.
If the user doesn't exist, signInWithOtp() will signup the user instead. To restrict this 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.
Magic links and OTPs share the same implementation. To send users a one-time code instead of a magic link, modify the magic link email template to include {{ .Token }} instead of {{ .ConfirmationURL }}.
Attempts a single-sign on using an enterprise Identity Provider. A
successful SSO attempt will redirect the current page to the identity
provider authorization page. The redirect URL is implementation and SSO
protocol specific.
If you've associated an email domain to the identity provider, you can use the domain property to start a sign-in flow.
In case you need to use a different way to start the authentication flow with an identity provider, you can use the providerId property. For example:
Mapping specific user email addresses with an identity provider.
Using different hints to identity the identity provider to be used by the user, like a company-specific page, IP address or other tracking information.
Parameters
params
REQUIRED
SignInWithSSO
// You can extract the user's email domain and use it to trigger the// authentication flow with the correct identity provider.const { data, error } = await supabase.auth.signInWithSSO({
domain: 'company.com' })
if (data?.url) {
// redirect the user to the identity provider's authentication flowwindow.location.href = data.url
}
Sign out a user
Inside a browser context, signOut() will remove the logged in user from the browser session and log them out - removing all items from localstorage and then trigger a "SIGNED_OUT" event.
In order to use the signOut() method, the user needs to be signed in first.
By default, signOut() uses the global scope, which signs out all other sessions that the user is logged into as well.
Since Supabase Auth uses JWTs for authentication, the access token JWT will be valid until it's expired. When the user signs out, Supabase revokes the refresh token and deletes the JWT from the client-side. This does not revoke the JWT and it will still be valid until it expires.
Parameters
options
Optional
SignOut
scope
Optional
"global" | "local" | "others"
Determines which sessions should be
logged out. Global means all
sessions by this account. Local
means only this session. Others
means all other sessions except the
current one. When using others,
there is no sign-out event fired on
the current session!
const { error } = await supabase.auth.signOut()
Send a password reset request
Sends a password reset request to an email address. This method supports the PKCE flow.
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().
A SIGNED_IN and PASSWORD_RECOVERY event will be emitted when the password recovery link is clicked.
You can use 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 to add additional redirect URLs to your project.
After the user has been redirected successfully, prompt them for a new password and call updateUser():
Log in a user given a User supplied OTP or TokenHash received through mobile or email.
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: email, recovery, invite or email_change (signup and magiclink types are deprecated).
The verification type used should be determined based on the corresponding auth method called before verifyOtp to sign up / sign-in a user.
The TokenHash is contained in the email templates and can be used to sign in. You may wish to use the hash with Magic Links for the PKCE flow for Server Side Auth. See this guide for more details.
Returns the session, refreshing it if necessary.
The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out.
This method retrieves the current local session (i.e local storage).
If the session has an expired access token, this method will use the refresh token to get a new session.
Returns a new session, regardless of expiry status.
Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession().
If the current session's refresh token is invalid, an error will be thrown.
This method will refresh and return a new session whether the current one is expired or not.
Parameters
currentSession
Optional
object
The current session. If passed in, it must contain a refresh token.
refresh_token
REQUIRED
string
const { data, error } = await supabase.auth.refreshSession()
const { session, user } = data
Retrieve a user
Gets the current user details if there is an existing session.
This method fetches the user object from the database instead of local session.
This method is useful for checking if the user is authorized because it validates the user's access token JWT on the server.
Should be used only when you require the most current user data. For faster results, getSession().session.user is recommended.
Parameters
jwt
Optional
string
Takes in an optional access token jwt. If no jwt is provided, getUser() will attempt to get the jwt from the current session.
const { data: { user } } = await supabase.auth.getUser()
Update a user
Updates user data for a logged in user.
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.
Parameters
attributes
REQUIRED
UserAttributes
data
Optional
object
A custom data object to store the user's metadata. This maps to the `auth.users.user_metadata` column.
The `data` should be a JSON object that includes user-specific info, such as their first and last name.
email
Optional
string
The user's email.
nonce
Optional
string
The nonce sent for reauthentication if the user's password is to be updated.
Call reauthenticate() to obtain the nonce first.
Sends a reauthentication OTP to the user's email or phone number.
Requires the user to be signed-in.
This method is used together with updateUser() when a user's password needs to be updated.
If you require your user to reauthenticate before updating their password, you need to enable the Secure password change option in your project's email provider settings.
A user is only require to reauthenticate before updating their password if Secure password change is enabled and the user hasn't recently signed in. A user is deemed recently signed in if the session was created in the last 24 hours.
This method will send a nonce to the user's email. If the user doesn't have a confirmed email address, the method will send the nonce to the user's confirmed phone number instead.
Sets the session data from the current session. If the current session is expired, setSession will take care of refreshing it to obtain a new session.
If the refresh token or access token in the current session is invalid, an error will be thrown.
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 is enabled by default on all projects to guard against replay attacks.
You can configure the REFRESH_TOKEN_REUSE_INTERVAL which provides a short window in which the same refresh token can be used multiple times in the event of concurrency or offline issues.
Parameters
currentSession
REQUIRED
object
The current session that minimally contains an access token and refresh token.
Receive a notification every time an auth event happens.
Types of auth events: INITIAL_SESSION, SIGNED_IN, SIGNED_OUT, TOKEN_REFRESHED, USER_UPDATED, PASSWORD_RECOVERY
The INITIAL_SESSION can be used to allow you to invoke the callback function when onAuthStateChange is first called.
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.
Parameters
callback
REQUIRED
function
A callback function to be invoked when an auth event happens.
This section contains methods commonly used for Multi-Factor Authentication (MFA) and are invoked behind the supabase.auth.mfa namespace.
Currently, we only support time-based one-time password (TOTP) as the 2nd factor. We don't support recovery codes but we allow users to enroll more than 1 TOTP factor, with an upper limit of 10.
Having a 2nd TOTP factor for recovery frees the user of the burden of having to store their recovery codes somewhere. It also reduces the attack surface since multiple recovery codes are usually generated compared to just having 1 backup TOTP factor.
Enroll a factor
Starts the enrollment process for a new Multi-Factor Authentication (MFA)
factor. This method creates a new unverified factor.
To verify a factor, present the QR code or secret to the user and ask them to add it to their
authenticator app.
The user has to enter the code from their authenticator app to verify it.
Currently, totp is the only supported factorType. The returned id should be used to create a challenge.
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
Create a challenge
Prepares a challenge used to verify that a user has access to a MFA
factor.
Helper method which creates a challenge and immediately uses the given code to verify against it thereafter. The verification code is
provided by the user by entering a code seen in their authenticator app.
An enrolled factor is required before invoking challengeAndVerify().
Returns the Authenticator Assurance Level (AAL) for the active session.
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.
Creates a new user.
This function should only be called on a server. Never expose your service_role key in the browser.
To confirm the user's email address or phone number, set email_confirm or phone_confirm to true. Both arguments default to false.
createUser() will not send a confirmation email to the user. You can use inviteUserByEmail() if you want to send them an email invite instead.
If you are sure that the created user's email or phone number is legitimate and verified, you can set the email_confirm or phone_confirm param to true.
Parameters
attributes
REQUIRED
AdminUserAttributes
app_metadata
Optional
object
A custom data object to store the user's application specific metadata. This maps to the `auth.users.app_metadata` column.
Only a service role can modify.
The `app_metadata` should be a JSON object that includes app-specific info, such as identity providers, roles, and other
access control information.
ban_duration
Optional
string
Determines how long a user is banned for.
The format for the ban duration follows a strict sequence of decimal numbers with a unit suffix.
Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
For example, some possible durations include: '300ms', '2h45m'.
Setting the ban duration to 'none' lifts the ban on the user.
email
Optional
string
The user's email.
email_confirm
Optional
boolean
Confirms the user's email address if set to true.
Only a service role can modify.
nonce
Optional
string
The nonce sent for reauthentication if the user's password is to be updated.
Call reauthenticate() to obtain the nonce first.
password
Optional
string
The user's password.
phone
Optional
string
The user's phone.
phone_confirm
Optional
boolean
Confirms the user's phone number if set to true.
Only a service role can modify.
role
Optional
string
The `role` claim set in the user's access token JWT.
When a user signs up, this role is set to `authenticated` by default. You should only modify the `role` if you need to provision several levels of admin access that have different permissions on individual columns in your database.
Setting this role to `service_role` is not recommended as it grants the user admin privileges.
user_metadata
Optional
object
A custom data object to store the user's metadata. This maps to the `auth.users.user_metadata` column.
The `user_metadata` should be a JSON object that includes user-specific info, such as their first and last name.
Note: When using the GoTrueAdminApi and wanting to modify a user's metadata,
this attribute is used instead of UserAttributes data.
The deleteUser() method requires the user's ID, which maps to the auth.users.id column.
Parameters
id
REQUIRED
string
The user id you want to remove.
shouldSoftDelete
Optional
boolean
If true, then the user will be soft-deleted from the auth schema.
Defaults to false for backward compatibility.
This function should only be called on a server. Never expose your `service_role` key in the browser.
The inviteUserByEmail() method is typically used by administrators to invite users to join the application.
Note that PKCE is not supported when using inviteUserByEmail. This is because the browser initiating the invite is often different from the browser acecpting the invite which makes it difficult to provide the security guarantees required of the PKCE flow.
Parameters
email
REQUIRED
string
The email address of the user.
options
Optional
object
Additional options to be included when inviting.
data
Optional
object
A custom data object to store additional metadata about the user. This maps to the `auth.users.user_metadata` column.
redirectTo
Optional
string
The URL which will be appended to the email link sent to the user's email address. Once clicked the user will end up on this URL.
Generates email links and OTPs to be sent via a custom email provider.
The following types can be passed into generateLink(): signup, magiclink, invite, recovery, email_change_current, email_change_new, phone_change.
generateLink() only generates the email link for email_change_email if the Secure email change is enabled in your project's email auth provider settings.
generateLink() handles the creation of the user for signup, invite and magiclink.
The data you want to update.
This function should only be called on a server. Never expose your `service_role` key in the browser.
app_metadata
Optional
object
A custom data object to store the user's application specific metadata. This maps to the `auth.users.app_metadata` column.
Only a service role can modify.
The `app_metadata` should be a JSON object that includes app-specific info, such as identity providers, roles, and other
access control information.
ban_duration
Optional
string
Determines how long a user is banned for.
The format for the ban duration follows a strict sequence of decimal numbers with a unit suffix.
Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
For example, some possible durations include: '300ms', '2h45m'.
Setting the ban duration to 'none' lifts the ban on the user.
email
Optional
string
The user's email.
email_confirm
Optional
boolean
Confirms the user's email address if set to true.
Only a service role can modify.
nonce
Optional
string
The nonce sent for reauthentication if the user's password is to be updated.
Call reauthenticate() to obtain the nonce first.
password
Optional
string
The user's password.
phone
Optional
string
The user's phone.
phone_confirm
Optional
boolean
Confirms the user's phone number if set to true.
Only a service role can modify.
role
Optional
string
The `role` claim set in the user's access token JWT.
When a user signs up, this role is set to `authenticated` by default. You should only modify the `role` if you need to provision several levels of admin access that have different permissions on individual columns in your database.
Setting this role to `service_role` is not recommended as it grants the user admin privileges.
user_metadata
Optional
object
A custom data object to store the user's metadata. This maps to the `auth.users.user_metadata` column.
The `user_metadata` should be a JSON object that includes user-specific info, such as their first and last name.
Note: When using the GoTrueAdminApi and wanting to modify a user's metadata,
this attribute is used instead of UserAttributes data.
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.
Parameters
functionName
REQUIRED
string
The name of the Function to invoke.
options
Optional
FunctionInvokeOptions
Options for invoking the Function.
body
Optional
object
The body of the request.
headers
Optional
object
Object representing the headers to send with the request.
By default, Broadcast and Presence are enabled for all projects.
By default, listening to database changes is disabled for new projects due to database performance and security concerns. You can turn it on by managing Realtime's replication.
You can receive the "previous" data for updates and deletes by setting the table's REPLICA IDENTITY to FULL (e.g., ALTER TABLE your_table REPLICA IDENTITY FULL;).
Row level security is not applied to delete statements. When RLS is enabled and replica identity is set to full, only the primary key is sent to clients.
Unsubscribes and removes Realtime channel from Realtime client.
Removing a channel is a great way to maintain the performance of your project's Realtime service as well as your database if you're listening to Postgres changes. Supabase will automatically handle cleanup 30 seconds after a client is disconnected, but unused channels may cause degradation as more clients are simultaneously subscribed.
Parameters
channel
REQUIRED
default
The name of the Realtime channel.
supabase.removeChannel(myChannel)
Unsubscribe from all channels
Unsubscribes and removes all Realtime channels from Realtime client.
Removing channels is a great way to maintain the performance of your project's Realtime service as well as your database if you're listening to Postgres changes. Supabase will automatically handle cleanup 30 seconds after a client is disconnected, but unused channels may cause degradation as more clients are simultaneously subscribed.
supabase.removeAllChannels()
Retrieve all channels
Returns all Realtime channels.
const channels = supabase.getChannels()
Broadcast a message
Sends a message into the channel.
Broadcast a message to all connected clients to a channel.
When using REST you don't need to subscribe to the channel
Refer to the Storage guide on how access control works
Parameters
id
REQUIRED
string
A unique identifier for the bucket you are creating.
options
Optional
object
public
REQUIRED
boolean
The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. By default, buckets are private.
allowedMimeTypes
Optional
object
specifies the allowed mime types that this bucket can accept during upload.
The default value is null, which allows files with all mime types to be uploaded.
Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png.
fileSizeLimit
Optional
null | string | number
specifies the max file size in bytes that can be uploaded to this bucket.
The global file size limit takes precedence over this value.
The default value is null, which doesn't set a per bucket file size limit.
Refer to the Storage guide on how access control works
Parameters
id
REQUIRED
string
A unique identifier for the bucket you are updating.
options
REQUIRED
object
public
REQUIRED
boolean
The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations.
allowedMimeTypes
Optional
object
specifies the allowed mime types that this bucket can accept during upload.
The default value is null, which allows files with all mime types to be uploaded.
Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png.
fileSizeLimit
Optional
null | string | number
specifies the max file size in bytes that can be uploaded to this bucket.
The global file size limit takes precedence over this value.
The default value is null, which doesn't set a per bucket file size limit.
objects table permissions: only insert when you are uploading new files and select, insert and update when you are upserting files
Refer to the Storage guide on how access control works
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.
Parameters
path
REQUIRED
string
The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.
fileBody
REQUIRED
FileBody
The body of the file to be stored in the bucket.
fileOptions
Optional
FileOptions
cacheControl
Optional
string
The number of seconds the asset is cached in the browser and in the Supabase CDN. This is set in the `Cache-Control: max-age=<seconds>` header. Defaults to 3600 seconds.
contentType
Optional
string
the `Content-Type` header value. Should be specified if using a `fileBody` that is neither `Blob` nor `File` nor `FormData`, otherwise will default to `text/plain;charset=UTF-8`.
duplex
Optional
string
The duplex option is a string parameter that enables or disables duplex streaming, allowing for both reading and writing data in the same stream. It can be passed as an option to the fetch() method.
upsert
Optional
boolean
When upsert is set to true, the file is overwritten if it exists. When set to false, an error is thrown if the object already exists. Defaults to false.
Downloads a file from a private bucket. For public buckets, make a request to the URL returned from getPublicUrl instead.
RLS policy permissions required:
buckets table permissions: none
objects table permissions: select
Refer to the Storage guide on how access control works
Parameters
path
REQUIRED
string
The full path and file name of the file to be downloaded. For example `folder/image.png`.
options
Optional
object
transform
Optional
TransformOptions
Transform the asset before serving it to the client.
format
Optional
"origin"
Specify the format of the image requested.
When using 'origin' we force the format to be the same as the original image.
When this option is not passed in, images are optimized to modern image formats like Webp.
height
Optional
number
The height of the image in pixels.
quality
Optional
number
Set the quality of the returned image.
A number from 20 to 100, with 100 being the highest quality.
Defaults to 80
resize
Optional
"cover" | "contain" | "fill"
The resize mode can be cover, contain or fill. Defaults to cover.
Cover resizes the image to maintain it's aspect ratio while filling the entire width and height.
Contain resizes the image to maintain it's aspect ratio while fitting the entire image within the width and height.
Fill resizes the image to fill the entire width and height. If the object's aspect ratio does not match the width and height, the image will be stretched to fit.
Replaces an existing file at the specified path with a new one.
RLS policy permissions required:
buckets table permissions: none
objects table permissions: update and select
Refer to the Storage guide 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.
Parameters
path
REQUIRED
string
The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to update.
fileBody
REQUIRED
object
The body of the file to be stored in the bucket.
fileOptions
Optional
FileOptions
cacheControl
Optional
string
The number of seconds the asset is cached in the browser and in the Supabase CDN. This is set in the `Cache-Control: max-age=<seconds>` header. Defaults to 3600 seconds.
contentType
Optional
string
the `Content-Type` header value. Should be specified if using a `fileBody` that is neither `Blob` nor `File` nor `FormData`, otherwise will default to `text/plain;charset=UTF-8`.
duplex
Optional
string
The duplex option is a string parameter that enables or disables duplex streaming, allowing for both reading and writing data in the same stream. It can be passed as an option to the fetch() method.
upsert
Optional
boolean
When upsert is set to true, the file is overwritten if it exists. When set to false, an error is thrown if the object already exists. Defaults to false.
Creates a signed URL. Use a signed URL to share a file for a fixed amount of time.
RLS policy permissions required:
buckets table permissions: none
objects table permissions: select
Refer to the Storage guide on how access control works
Parameters
path
REQUIRED
string
The file path, including the current file name. For example `folder/image.png`.
expiresIn
REQUIRED
number
The number of seconds until the signed URL expires. For example, `60` for a URL which is valid for one minute.
options
Optional
object
download
Optional
string | boolean
triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename.
transform
Optional
TransformOptions
Transform the asset before serving it to the client.
format
Optional
"origin"
Specify the format of the image requested.
When using 'origin' we force the format to be the same as the original image.
When this option is not passed in, images are optimized to modern image formats like Webp.
height
Optional
number
The height of the image in pixels.
quality
Optional
number
Set the quality of the returned image.
A number from 20 to 100, with 100 being the highest quality.
Defaults to 80
resize
Optional
"cover" | "contain" | "fill"
The resize mode can be cover, contain or fill. Defaults to cover.
Cover resizes the image to maintain it's aspect ratio while filling the entire width and height.
Contain resizes the image to maintain it's aspect ratio while fitting the entire image within the width and height.
Fill resizes the image to fill the entire width and height. If the object's aspect ratio does not match the width and height, the image will be stretched to fit.
Creates multiple signed URLs. Use a signed URL to share a file for a fixed amount of time.
RLS policy permissions required:
buckets table permissions: none
objects table permissions: select
Refer to the Storage guide on how access control works
Parameters
paths
REQUIRED
string[]
The file paths to be downloaded, including the current file names. For example `['folder/image.png', 'folder2/image2.png']`.
expiresIn
REQUIRED
number
The number of seconds until the signed URLs expire. For example, `60` for URLs which are valid for one minute.
options
Optional
object
download
REQUIRED
string | boolean
triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename.
Upload a file with a token generated from createSignedUploadUrl.
RLS policy permissions required:
buckets table permissions: none
objects table permissions: none
Refer to the Storage guide on how access control works
Parameters
path
REQUIRED
string
The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.
token
REQUIRED
string
The token generated from `createSignedUploadUrl`
fileBody
REQUIRED
FileBody
The body of the file to be stored in the bucket.
fileOptions
Optional
FileOptions
cacheControl
Optional
string
The number of seconds the asset is cached in the browser and in the Supabase CDN. This is set in the `Cache-Control: max-age=<seconds>` header. Defaults to 3600 seconds.
contentType
Optional
string
the `Content-Type` header value. Should be specified if using a `fileBody` that is neither `Blob` nor `File` nor `FormData`, otherwise will default to `text/plain;charset=UTF-8`.
duplex
Optional
string
The duplex option is a string parameter that enables or disables duplex streaming, allowing for both reading and writing data in the same stream. It can be passed as an option to the fetch() method.
upsert
Optional
boolean
When upsert is set to true, the file is overwritten if it exists. When set to false, an error is thrown if the object already exists. Defaults to false.
A simple convenience function to get the URL for an asset in a public bucket. If you do not want to use this function, you can construct the public URL by concatenating the bucket URL with the path to the asset.
This function does not verify if the bucket is public. If a public URL is created for a bucket which is not public, you will not be able to download the asset.
The bucket needs to be set to public, either via updateBucket() or by going to Storage on supabase.com/dashboard, clicking the overflow menu on a bucket and choosing "Make public"
RLS policy permissions required:
buckets table permissions: none
objects table permissions: none
Refer to the Storage guide on how access control works
Parameters
path
REQUIRED
string
The path and name of the file to generate the public URL for. For example `folder/image.png`.
options
Optional
object
download
Optional
string | boolean
Triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename.
transform
Optional
TransformOptions
Transform the asset before serving it to the client.
format
Optional
"origin"
Specify the format of the image requested.
When using 'origin' we force the format to be the same as the original image.
When this option is not passed in, images are optimized to modern image formats like Webp.
height
Optional
number
The height of the image in pixels.
quality
Optional
number
Set the quality of the returned image.
A number from 20 to 100, with 100 being the highest quality.
Defaults to 80
resize
Optional
"cover" | "contain" | "fill"
The resize mode can be cover, contain or fill. Defaults to cover.
Cover resizes the image to maintain it's aspect ratio while filling the entire width and height.
Contain resizes the image to maintain it's aspect ratio while fitting the entire image within the width and height.
Fill resizes the image to fill the entire width and height. If the object's aspect ratio does not match the width and height, the image will be stretched to fit.
width
Optional
number
The width of the image in pixels.
const { data } = supabase
.storage
.from('public-bucket')
.getPublicUrl('folder/avatar1.png')