Kotlin Reference v1.0

kotlin Client Library

@supabase-community/supabase-ktView on GitHub

This reference documents every object and method available in Supabase's Kotlin Multiplatform library, supabase-kt. You can use supabase-kt to interact with your Postgres database, listen to database changes, invoke Deno Edge Functions, build login and user management functionality, and manage large files.

To see supported Kotlin targets, check the corresponding module README on GitHub.

To migrate from version 1.4.X to 2.0.0, see the migration guide


Initializing

Create Supabase Client

Independently of which Supabase module you are using, you will need to initialize the main client first and install the module.

To create a new client, you can use the createSupabaseClient function.

When installing a module, you can pass a block to configure it.

supabase-kt provides several platform implementations for OAuth and OTP link verification.
On JVM, it uses a HTTP Callback Server to receive the session data from a successful OAuth login.

Note: OTP link verification such as sign ups are not supported on JVM. You may have to send a verification token rather than a url in your E-Mail. To send the token, rather than a redirect url, you have to change {{ .ConfirmationURL }} in your sign up email to {{ .Token }}

On Android, IOS & MacOS, it uses deeplinks. Refer to the guide below on how to setup deeplinks. Alternatively you could use Native Google Auth or a WebView for OAuth. Refer to our demo to learn more. On JS, it uses the website origin as the callback url. Session importing gets handled automatically. Windows, tvOS, watchOS & Linux currently have no default implementation. Feel free to create a PR.

You always make your own implementation and use gotrue.parseSessionFromFragment(fragment) or gotrue.parseSessionFromUrl(url) to let supabase-kt handle the parsing after receiving a callback. Then you can simply use gotrue.importSession(session).

Deeplinks are supported on Android, IOS and MacOS.

  1. Setup a deeplink for you app
    On Android you may setup a deeplink in your Android manifest.
    On IOS & MacOS you may setup a url scheme.
  2. Add your deeplink to the redirect URLs
    Pattern: scheme://host
  3. Configure the GoTrue plugin You have to set the host and the scheme in the GoTrue config:

    _10
    install(GoTrue) {
    _10
    host = "deeplink host" // this can be anything, eg. your package name or app/company url (not your supabase url)
    _10
    scheme = "deeplink scheme"
    _10
    _10
    //Android only, you can also change that OAuth/SSO logins open in a custom tab, rather than an external browser:
    _10
    defaultExternalAuthAction = ExternalAuthAction.CUSTOM_TABS //defaults to EXTERNAL_BROWSER
    _10
    }

  4. Call platform specific function on startup
    On Android: supabase.handleDeeplinks(intent)
    On IOS/MacOS: supabase.handleDeeplinks(url)

Then you can just login using OAuth:


_10
supabase.gotrue.loginWith(Google)

Or open OTP links directly in your app.

PKCE Authentication flow

supabase-kt supports the PKCE authentication flow. To use it, you just have to change the flowType in the GoTrue configuration:


_10
install(GoTrue) {
_10
flowType = FlowType.PKCE
_10
}

That's it! If you already implemented deeplinks to handle OTPs and OAuth you don't have to change anything!


_10
val supabase = createSupabaseClient(
_10
supabaseUrl = "https://xyzcompany.supabase.co",
_10
supabaseKey = "public-anon-key"
_10
) {
_10
install(GoTrue)
_10
install(Postgrest)
_10
//install other modules
_10
}


Fetch data

Perform a SELECT query on the table or view.

  • When calling a decode method, you have to provide a serializable class as the type parameter.
  • You can provide a Columns object to select specific columns.
  • You can provide a filter block to filter the results

_10
val city = supabase.postgrest["cities"].select().decodeSingle<City>()


Insert data

  • When calling an insert method, you have to provide a serializable value.
  • By default, every time you run insert(), the client library will make a select to return the full record. This is convenient, but it can also cause problems if your policies are not configured to allow the select operation. If you are using Row Level Security and you are encountering problems, try setting the returning param to Returning.MINIMAL.

_10
val city = City(name = "The Shire", countryId = 554)
_10
supabase.postgrest["cities"].insert(city, returning = Returning.MINIMAL) //returning defaults to Returning.REPRESENTATION


Update data

  • update() should always be combined with a filter block to avoid updating all records.
  • When calling insert or update, you have to provide a serializable value in the function parameter.

_11
supabase.postgrest["countries"].update(
_11
{
_11
Country::name setTo "Australia"
_11
//or
_11
set("name", "Australia")
_11
}
_11
) {
_11
Country::id eq 1
_11
//or
_11
eq("id", 1)
_11
}


Upsert data

  • Primary keys should be included in the data payload in order for an update to work correctly.
  • Primary keys must be natural, not surrogate. There are however, workarounds for surrogate primary keys.
  • If you need to insert new data and update existing data at the same time, use Postgres triggers.
  • When calling insert or update, you have to provide a serializable value in the function parameter.

_10
val toUpsert = Message(id = 3, message = "foo", username = "supabot")
_10
supabase.postgrest["messages"].insert(toUpsert, upsert = true)


Delete data

  • delete() should always be combined with a filter block 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.

_10
supabase.postgrest["cities"].delete {
_10
City::id eq 666
_10
//or
_10
eq("id", 666)
_10
}


Call a Postgres function

You can call stored procedures as a "Remote Procedure Call".

That's a fancy way of saying that you can put some logic into your database then call it from anywhere. It's especially useful when the logic rarely changes - like password resets and updates.

  • When calling rpc with parameters, you have to provide a serializable value in the function parameter.

_10
supabase.postgrest.rpc("hello_world")


Using filters

Filters allow you to only return rows that match certain conditions.

Filters can be used on select(), update(), and delete() queries.

You can use two different types for applying filters:


_10
eq("country_id", 1)

And using a class property:


_10
City::countryId eq 1

As you can see on the property syntax: the name of the countryId gets converted to country_id.

By default, this is done by converting camel case to snake case, but you can customize this by changing the PropertyConversionMethod in the Postgrest Config

If a database function returns a table response, you can also apply filters.


_10
supabase.postgrest["cities"].select(columns = Columns.list("name", "country_id")) {
_10
City::name eq "The Shire"
_10
//or
_10
eq("name", "The Shire")
_10
}


Column is equal to a value

Finds all rows whose value on the stated column exactly matches the specified value.


_10
supabase.postgrest["cities"].select(columns = Columns.list("name", "country_id")) {
_10
City::name eq "The Shire"
_10
//or
_10
eq("name", "The Shire")
_10
}


Column is not equal to a value

Finds all rows whose value on the stated column doesn't match the specified value.


_10
supabase.postgrest["cities"].select(columns = Columns.list("name", "country_id")) {
_10
City::name neq "The Shire"
_10
//or
_10
neq("name", "The Shire")
_10
}


Column is greater than a value

Finds all rows whose value on the stated column is greater than the specified value.


_10
supabase.postgrest["cities"].select(columns = Columns.list("name")) {
_10
City::countryId gt 300
_10
//or
_10
gt("country_id", 300)
_10
}


Column is greater than or equal to a value

Finds all rows whose value on the stated column is greater than or equal to the specified value.


_10
supabase.postgrest["cities"].select(columns = Columns.list("name")) {
_10
City::countryId gte 300
_10
//or
_10
gte("country_id", 300)
_10
}


Column is less than a value

Finds all rows whose value on the stated column is less than the specified value.


_10
supabase.postgrest["cities"].select(columns = Columns.list("name")) {
_10
City::countryId lt 300
_10
//or
_10
lt("country_id", 300)
_10
}


Column is less than or equal to a value

Finds all rows whose value on the stated column is less than or equal to the specified value.


_10
supabase.postgrest["cities"].select(columns = Columns.list("name")) {
_10
City::countryId lte 300
_10
//or
_10
lte("country_id", 300)
_10
}


Column matches a pattern

Finds all rows whose value in the stated column matches the supplied pattern (case sensitive).


_10
supabase.postgrest["cities"].select(columns = Columns.list("name")) {
_10
City::name like "%la%"
_10
//or
_10
like("name", "%la%")
_10
}


Column matches a case-insensitive pattern

Finds all rows whose value in the stated column matches the supplied pattern (case insensitive).


_10
supabase.postgrest["cities"].select(columns = Columns.list("name")) {
_10
City::name ilike "%la%"
_10
//or
_10
ilike("name", "%la%")
_10
}


Column is a value

A check for exact equality (null, true, false), finds all rows whose value on the stated column exactly match the specified value.

is_ and in_ filter methods are suffixed with _ to avoid collisions with reserved keywords.


_10
supabase.postgrest["cities"].select(columns = Columns.list("name")) {
_10
City::name isExact null
_10
//or
_10
exact("name", null)
_10
}


Column is in an array

Finds all rows whose value on the stated column is found on the specified values.


_10
supabase.postgrest["cities"].select(columns = Columns.list("name")) {
_10
City::name isIn listOf("Rio de Janeiro", "San Francisco")
_10
//or
_10
isIn("name", listOf("Rio de Janeiro", "San Francisco"))
_10
}


Column contains every element in a value


_10
supabase.postgrest["cities"].select(columns = Columns.list("name")) {
_10
City::mainExports contains listOf("oil")
_10
//or
_10
contains("main_exports", listOf("oil"))
_10
}


Greater than a range

Only relevant for range columns. Match only rows where every element in column is greater than any element in range.


_10
supabase.postgrest["reservations"].select {
_10
Reservation::during rangeGt ("2000-01-02 08:30" to "2000-01-02 09:30")
_10
//or
_10
rangeGt("during", "2000-01-02 08:30" to "2000-01-02 09:30")
_10
}


Greater than or equal to a range

Only relevant for range columns. Match only rows where every element in column is either contained in range or greater than any element in range.


_10
supabase.postgrest["reservations"].select {
_10
Reservation::during rangeGte ("2000-01-02 08:30" to "2000-01-02 09:30")
_10
//or
_10
rangeGte("during", "2000-01-02 08:30" to "2000-01-02 09:30")
_10
}


Less than a range

Only relevant for range columns. Match only rows where every element in column is less than any element in range.


_10
supabase.postgrest["reservations"].select {
_10
Reservation::during rangeLt ("2000-01-02 08:30" to "2000-01-02 09:30")
_10
//or
_10
rangeLt("during", "2000-01-02 08:30" to "2000-01-02 09:30")
_10
}


Less than or equal to a range

Only relevant for range columns. Match only rows where every element in column is either contained in range or less than any element in range.


_10
supabase.postgrest["reservations"].select {
_10
Reservation::during rangeLte ("2000-01-02 08:30" to "2000-01-02 09:30")
_10
//or
_10
rangeLte("during", "2000-01-02 08:30" to "2000-01-02 09:30")
_10
}


Mutually exclusive to a range

Only relevant for range columns. Match only rows where column is mutually exclusive to range and there can be no element between the two ranges.


_10
supabase.postgrest["reservations"].select {
_10
Reservation::during adjacent ("2000-01-02 08:30" to "2000-01-02 09:30")
_10
//or
_10
adjacent("during", "2000-01-02 08:30" to "2000-01-02 09:30")
_10
}


With a common element

Only relevant for array and range columns. Match only rows where column and value have an element in common.


_10
supabase.postgrest["issues"].select(columns = Columns.list("title")) {
_10
Issue::tags overlaps listOf("is:closed", "severity:high")
_10
//or
_10
overlaps("tags", listOf("is:closed", "severity:high"))
_10
}


Match a string

Only relevant for text and tsvector columns. Match only rows where column matches the query string in query.

For more information, see Postgres full text search.


Don't match the filter

Finds all rows that don't satisfy the filter.

  • .filterNot() expects you to use the raw PostgREST syntax for the filter names and values.

_10
supabase.postgrest["countries"].select {
_10
filterNot("name", FilterOperation.IS, "")
_10
}


Match at least one filter

Finds all rows satisfying at least one of the filters.


_10
supabase.postgrest["countries"].select(columns = Columns.list("name")) {
_10
or {
_10
Country::id eq 2
_10
Country::name eq "Algeria"
_10
//or
_10
eq("id", 2)
_10
eq("name", "Algeria")
_10
}
_10
}


Match the filter

filter() expects you to use the raw PostgREST syntax for the filter values.


_10
supabase.postgrest["countries"].select {
_10
filter(column = "name", operator = FilterOperator.IN, value = "('Algeria', 'Japan')")
_10
}


Overview

  • The auth methods can be accessed via the Supabase GoTrue Auth client.

_10
val supabase = createSupabaseClient(supabaseURL = "https://xyzcompany.supabase.co'", supabaseKey = "public-anon-key") { ... }
_10
val gotrue = supabase.gotrue


Create a new user

Creates a new user.

  • By default, the user needs to verify their email address before logging in. To turn this off, disable Confirm email in your project.
  • Confirm email determines if users need to confirm their email address after signing up.
    • If Confirm email is enabled, the return value is the user and you won't be logged in automatically.
    • If Confirm email is disabled, the return value is null and you will be logged in instead.
  • 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.
  • To learn how to handle OTP links & OAuth refer to initializing
  • If signUpWith() 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.

_10
val user = supabase.gotrue.signUpWith(Email) {
_10
email = "example@email.com"
_10
password = "example-password"
_10
}


Listen to auth events

Listen to session changes.


_10
supabase.gotrue.sessionStatus.collect {
_10
when(it) {
_10
is SessionStatus.Authenticated -> println(it.session.user)
_10
SessionStatus.LoadingFromStorage -> println("Loading from storage")
_10
SessionStatus.NetworkError -> println("Network error")
_10
SessionStatus.NotAuthenticated -> println("Not authenticated")
_10
}
_10
}


Sign in a user

Logs in an existing user.

  • Requires either an email and password or a phone number and password.

_10
supabase.gotrue.loginWith(Email) {
_10
email = "example@email.com"
_10
password = "example-password"
_10
}


Sign in a user through OTP

Sends a OTP to the user's email or phone number.

  • 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, sendOtpTo() will signup the user instead. To restrict this behavior, you can set createUser 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.
  • See redirect URLs and wildcards to add additional redirect URLs to your project.
  • To learn how to handle OTP links & OAuth refer to initializing
  • 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 }}.

_10
supabase.gotrue.sendOtpTo(Email) {
_10
email = "example@email.com"
_10
}


Sign in a user through OAuth

  • This method is used for signing in using a third-party provider.
  • Supabase supports many different third-party providers.
  • To learn how to handle OTP links & OAuth refer to initializing

_10
supabase.gotrue.loginWith(Github)


Sign in a user through SSO

  • Before you can call this method you need to establish a connection to an identity provider. Use the CLI commands to do this.
  • If you've associated an email domain to the identity provider, you can use the SSO.withDomain() function in the loginWith method 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 SSO.withProviderId function. For example:
    • Mapping specific user email addresses with an identity provider.
    • Using different hints to identity the identity provider to be used by the user, like a company-specific page, IP address or other tracking information.
  • To learn how to handle OTP links & OAuth refer to initializing

_10
// You can extract the user's email domain and use it to trigger the
_10
// authentication flow with the correct identity provider.
_10
_10
supabase.gotrue.loginWith(SSO.withDomain("company.com"))
_10
_10
//the url was opened automatically, if you don't want that, provide a custom redirect url


Sign out a user

Logs out the current user.

  • In order to use the logout() method, the user needs to be signed in first.

_10
supabase.gotrue.logout()


Send a password reset request

Sends a password reset request to the given email address.

  • 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 sendRecoveryEmail() only sends a password reset link to the user's email. To update the user's password, see modifyUser().
  • The user gets redirected back to your app, assuming you setup OTP handling
  • After the user has been redirected successfully, prompt them for a new password and call modifyUser():

    _10
    supabase.gotrue.modifyUser {
    _10
    password = "1234567"
    _10
    }


_10
supabase.gotrue.sendRecoveryEmail(email = "example@email.com")


Verify and log in through OTP

Log in a user given a User supplied OTP received via mobile.


_10
supabase.gotrue.verifyEmailOtp(type = OtpType.Email.INVITE, email = "example@email.com", token = "token")


Retrieve a session

Returns the current session, or null if there is none.


_10
val session = supabase.gotrue.currentSessionOrNull()


Retrieve a new session

This method will refresh the session whether the current one is expired or not.

  • This is done automatically, but can be disabled in the GoTrue config.

_10
val session = supabase.gotrue.refreshCurrentSession()


Retrieve a user

  • This method gets the user object from the current session.
  • Fetches the user object from the database instead of local session.
  • Should be used only when you require the most current user data. For faster results, getCurrentSessionOrNull()?.user is recommended.

_10
val user = supabase.gotrue.retrieveUserForCurrentSession(updateSession = true)


Update a user

Modifies the user data.

  • In order to use the modifyUser() 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.

_10
val user = supabase.gotrue.modifyUser {
_10
email = "newEmail@email.com"
_10
}


Send a password reauthentication nonce

  • This method is used together with modifyUser() when a user's password needs to be updated.
  • 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.

_10
supabase.gotrue.reauthenticate()


Resend an OTP

  • Resends a signup confirmation, email change or phone change email to the user.
  • Passwordless sign-ins can be resent by calling the sendOtpTo() method again.
  • Password recovery emails can be resent by calling the sendRecoveryEmail() method again.
  • This method will only resend an email or phone OTP to the user if there was an initial signup, email change or phone change request being made.

_10
supabase.gotrue.resendEmail(OtpType.Email.SIGNUP, "example@email.com")


Set the session data

Changes the local session.

  • importSession() takes in a UserSession.
  • 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.

_10
supabase.gotrue.importSession(UserSession(accessToken = "token", refreshToken = "refresh", expiresIn = 2000, tokenType = "Bearer", user = null))


Exchange an auth code for a session

  • Used when flowType is set to FlowType.PKCE in the GoTrue configuration.

_10
supabase.gotrue.exchangeCodeForSession("34e770dd-9ff9-416c-87fa-43b31d7ef225")


Auth MFA

This section contains methods commonly used for Multi-Factor Authentication (MFA) and are invoked behind the supabase.gotrue.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

Enrolls a new factor.


_10
val factor = supabase.gotrue.mfa.enroll(factorType = FactorType.TOTP)
_10
_10
// Use the id to create a challenge.
_10
// The challenge can be verified by entering the code generated from the authenticator app.
_10
// The code will be generated upon scanning the qr_code or entering the secret into the authenticator app.
_10
val (id, type, qrCode) = factor.data //qrCode is a svg as a string
_10
val (factorId, factorType, _) = factor


Create a challenge

Creates a challenge for a factor.


_10
val challenge = supabase.gotrue.mfa.createChallenge(factorId = "34e770dd-9ff9-416c-87fa-43b31d7ef225")


Verify a challenge

Verifies a challenge for a factor.


_10
supabase.gotrue.mfa.verifyChallenge(
_10
factorId = "34e770dd-9ff9-416c-87fa-43b31d7ef225",
_10
challengeId = "4034ae6f-a8ce-4fb5-8ee5-69a5863a7c15",
_10
code = "123456",
_10
saveSession = true // this is set to true by default, but you can set it to false if you want to handle the session yourself
_10
)


Create and verify a challenge

Creates and verifies a challenge for a factor.


_10
supabase.gotrue.mfa.createChallengeAndVerify(
_10
factorId = "34e770dd-9ff9-416c-87fa-43b31d7ef225",
_10
code = "123456",
_10
saveSession = true // this is set to true by default, but you can set it to false if you want to handle the session yourself
_10
)


Unenroll a factor

Unenroll removes a MFA factor. A user has to have an AAL2 authentication level in order to unenroll a verified factor.


_10
supabase.gotrue.mfa.unenroll(factorId = "34e770dd-9ff9-416c-87fa-43b31d7ef225")


Get Authenticator Assurance Level

  • Authenticator Assurance Level (AAL) is the measure of the strength of an authentication mechanism.
  • In Supabase, having an AAL of aal1 refers to having the 1st factor of authentication such as an email and password or OAuth sign-in while aal2 refers to the 2nd factor of authentication such as a time-based, one-time-password (TOTP).
  • If the user has a verified factor, the next field will return AuthenticatorAssuranceLevel.AAL2, else, it will return AuthenticatorAssuranceLevel.AAL1.

_10
val (current, next) = supabase.gotrue.mfa.getAuthenticatorAssuranceLevel()


Auth Admin

  • Any method under the supabase.gotrue.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.

_14
val supabase = createSupabaseClient(
_14
supabaseUrl = "https://id.supabase.co",
_14
supabaseKey = "supabaseKey"
_14
) {
_14
install(GoTrue) {
_14
autoLoadFromStorage = false
_14
alwaysAutoRefresh = false
_14
}
_14
// install other plugins (these will use the service role key)
_14
}
_14
supabase.gotrue.importAuthToken("service_role")
_14
_14
// Access auth admin api
_14
val adminGoTrueClient = supabase.gotrue.admin


Retrieve a user

Fetches the user object from the database based on the user's id.

  • The retrieveUserById() method requires the user's id which maps to the auth.users.id column.

_10
val user = supabase.gotrue.admin.retrieveUserById(uid = "f2a0b0a0-6b1a-4b7a-8f1a-4b7a6b1a8f1a")


List all users

Retrieves a list of users.

  • Defaults to return 50 users per page.

_10
val users = supabase.gotrue.admin.retrieveUsers()


Create a user

Creates a new user.

  • To confirm the user's email address or phone number, set autoConfirm to true. Both arguments default to false.

_10
val userWithEmail = supabase.gotrue.admin.createUserWithEmail {
_10
email = "example@email.com"
_10
password = "secretpassword"
_10
userMetadata {
_10
put("name", "John")
_10
}
_10
}


Delete a user

Deletes a user from the database.

  • The deleteUser() method requires the user's ID, which maps to the auth.users.id column.

_10
supabase.gotrue.admin.deleteUser(uid = "uid")


Send an email invite link

Sends an invite link to the user's email address.


_10
supabase.gotrue.admin.inviteUserByEmail(
_10
email = "example@email.com",
_10
//optional:
_10
redirectTo = "https://example.com/redirect",
_10
data = buildJsonObject {
_10
put("custom", "value")
_10
}
_10
)



Update a user

Updates the user data.


_10
supabase.gotrue.admin.updateUserById(uid = "id") {
_10
email = "example@email.com"
_10
}


List all factors for a user

Lists all factors associated to a user.


_10
const factors = supabase.gotrue.admin.retrieveFactors(uid = "id")


Delete a factor for a user

Deletes a factor on a user. This will log the user out of all active sessions if the deleted factor was verified.


_10
supabase.gotrue.admin.deleteFactor(uid = "id", factorId = "factor_id")


Invokes a Supabase Edge Function.

Invokes a Supabase Function. See the guide for details on writing Functions.

  • When invoking a function with parameters, you have to provide a serializable value in the function parameter.

  • Requires an Authorization header.


_10
supabase.functions.invoke("function_name")


Subscribe to channel

Subscribe to realtime changes in your database.

  • Realtime is disabled by default for new Projects for better database performance and security. You can turn it on by managing replication.
  • If you want to receive the "previous" data for updates and deletes, you will need to set REPLICA IDENTITY to FULL, like this: ALTER TABLE your_table REPLICA IDENTITY FULL;
  • When using a method with a generic type like track, broadcast or broadcastFlow, you have to provide a serializable class as the type parameter.

_10
supabase.realtime.connect()


Unsubscribe from a channel

Unsubscribes and removes Realtime channel from Realtime client.

  • Removing a channel is a great way to maintain the performance of your project's Realtime service as well as your database if you're listening to Postgres changes.
  • Supabase will automatically handle cleanup 30 seconds after a client is disconnected, but unused channels may cause degradation as more clients are simultaneously subscribed.

_10
val channel = supabase.realtime.createChannel("channelId") {
_10
//optional config
_10
}
_10
//...
_10
supabase.realtime.removeChannel(channel)


Unsubscribe from all channels

Unsubscribes and removes all Realtime channels from Realtime client.

  • Removing channels is a great way to maintain the performance of your project's Realtime service as well as your database if you're listening to Postgres changes. Supabase will automatically handle cleanup 30 seconds after a client is disconnected, but unused channels may cause degradation as more clients are simultaneously subscribed.

_10
supabase.realtime.removeAllChannels()


Retrieve all channels

Returns all Realtime channels.


_10
val channels = supabase.realtime.subscriptions.entries


Create a bucket

  • RLS policy permissions required:
    • buckets table permissions: insert
    • objects table permissions: none
  • Refer to the Storage guide on how access control works

_10
supabase.storage.createBucket(name = "icons", id = "icons") {
_10
public = true
_10
fileSizeLimit = 5.megabytes
_10
}


Retrieve a bucket

  • RLS policy permissions required:
    • buckets table permissions: select
    • objects table permissions: none
  • Refer to the Storage guide on how access control works

_10
val bucket = supabase.storage.retrieveBucketById(bucketId = "avatars")


List all buckets

  • RLS policy permissions required:
    • buckets table permissions: select
    • objects table permissions: none
  • Refer to the Storage guide on how access control works

_10
val buckets = supabase.storage.retrieveBuckets()


Update a bucket

  • RLS policy permissions required:
    • buckets table permissions: select and update
    • objects table permissions: none
  • Refer to the Storage guide on how access control works

_10
supabase.storage.updateBucket("cards") {
_10
public = false
_10
fileSizeLimit = 20.megabytes
_10
allowedMimeTypes(ContentType.Image.PNG, ContentType.Image.JPEG)
_10
}


Delete a bucket

  • RLS policy permissions required:
    • buckets table permissions: select and delete
    • objects table permissions: none
  • Refer to the Storage guide on how access control works

_10
supabase.storage.deleteBucket(bucketId = "icons")


Empty a bucket

  • RLS policy permissions required:
    • buckets table permissions: select
    • objects table permissions: select and delete
  • Refer to the Storage guide on how access control works

_10
supabase.storage.emptyBucket(bucketId = "icons")


Upload a file

  • RLS policy permissions required:
    • buckets table permissions: none
    • objects table permissions: insert
  • Refer to the Storage guide on how access control works
  • Resumable uploads use a Disk cache by default to store the upload urls. You can customize that in the GoTrue config by changing the resumable.cache property.

_10
val bucket = supabase.storage["avatars"]
_10
bucket.upload("myIcon.png", byteArray, upsert = false)
_10
//on JVM you can use java.io.File
_10
bucket.upload("myIcon.png", file, upsert = false)


Download a file

  • RLS policy permissions required:
    • buckets table permissions: none
    • objects table permissions: select
  • Refer to the Storage guide on how access control works

_10
val bucket = supabase.storage["avatars"]
_10
val bytes = bucket.downloadAuthenticated("test.png")
_10
//or on JVM:
_10
bucket.downloadAuthenticatedTo("test.png", File("test.png"))


List all files in a bucket

  • RLS policy permissions required:
    • buckets table permissions: none
    • objects table permissions: select
  • Refer to the Storage guide on how access control works

_10
val bucket = supabase.storage["avatars"]
_10
val files = bucket.list()


Replace an existing file

  • RLS policy permissions required:
    • buckets table permissions: none
    • objects table permissions: update and select
  • Refer to the Storage guide on how access control works

_10
val bucket = supabase.storage["avatars"]
_10
bucket.update("myIcon.png", byteArray, upsert = false)
_10
//on JVM you can use java.io.File
_10
bucket.update("myIcon.png", file, upsert = false)


Move an existing file

  • RLS policy permissions required:
    • buckets table permissions: none
    • objects table permissions: update and select
  • Refer to the Storage guide on how access control works

_10
val bucket = supabase.storage["avatars"]
_10
bucket.move("icon1.png", "icon2.png")


Copy an existing file

  • RLS policy permissions required:
    • buckets table permissions: none
    • objects table permissions: insert and select
  • Refer to the Storage guide on how access control works

_10
supabase.storage["test"].copy(from = "avatar.png", to = "avatar2.png")


Delete files in a bucket

  • RLS policy permissions required:
    • buckets table permissions: none
    • objects table permissions: delete and select
  • Refer to the Storage guide on how access control works

_10
val bucket = supabase.storage["avatars"]
_10
bucket.delete("test.png", "test2.png")


Create a signed URL

  • RLS policy permissions required:
    • buckets table permissions: none
    • objects table permissions: select
  • Refer to the Storage guide on how access control works

_10
val bucket = supabase.storage["avatars"]
_10
val url = bucket.createSignedUrl(path = "icon.png", expiresIn = 3.minutes)


Create signed URLs

  • RLS policy permissions required:
    • buckets table permissions: none
    • objects table permissions: select
  • Refer to the Storage guide on how access control works

_10
val urls = supabase.storage["avatars"].createSignedUrls(20.minutes, "avata1.jpg", "avatar2.jpg")


Create signed upload URL

  • RLS policy permissions required:
    • buckets table permissions: none
    • objects table permissions: insert
  • Refer to the Storage guide on how access control works

_10
val url = supabase.storage["avatars"].createSignedUploadUrl("avatar.png")


Upload to a signed URL

  • RLS policy permissions required:
    • buckets table permissions: none
    • objects table permissions: none
  • Refer to the Storage guide on how access control works

_10
supabase.storage["avatars"].uploadToSignedUrl(path = "avatar.jpg", token = "token-from-createSignedUploadUrl", data = bytes)
_10
//or on JVM:
_10
supabase.storage["avatars"].uploadToSignedUrl(path = "avatar.jpg", token = "token-from-createSignedUploadUrl", file = File("avatar.jpg"))


Retrieve public URL

  • The bucket needs to be set to public, either via updateBucket() or by going to Storage on supabase.com/dashboard, clicking the overflow menu on a bucket and choosing "Make public"
  • RLS policy permissions required:
    • buckets table permissions: none
    • objects table permissions: none
  • Refer to the Storage guide on how access control works

_10
val url = supabase.storage["public-bucket"].publicUrl("folder/avatar1.png")