Home

Kotlin Client Library

@supabase-community/supabase-kt

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.

Supported Kotlin targets:

  • JVM
  • Android
  • iOS (Experimental)
  • JS (Browser)

The Kotlin client library is created and maintained by the Supabase community, and is not an official library. Please be tolerant of areas where the library is still being developed, and — as with all the libraries — feel free to contribute wherever you find issues.

Huge thanks to official maintainer, jan-tennert.

Installing

Add one or more modules to your project#

latest stable supabase-kt versionlatest supabase-kt version

Add dependency to your build file:

implementation("io.github.jan-tennert.supabase:[module]:VERSION")

The available modules are: gotrue-kt, realtime-kt, storage-kt, functions-kt, postgrest-kt and apollo-graphql

When using multiple modules, you can also use the BOM dependency to ensure that all modules use the same version:

implementation(platform("io.github.jan-tennert.supabase:bom:VERSION"))
implementation("io.github.jan-tennert.supabase:postgrest-kt")
implementation("io.github.jan-tennert.supabase:realtime-kt")

Add Ktor Client Engine to each of your Kotlin targets (required)#

You can find a list of engines here

implementation("io.ktor:ktor-client-[engine]:KTOR_VERSION")

Multiplatform example:

val commonMain by getting {
    dependencies {
        //supabase modules
    }
}
val jvmMain by getting {
    dependencies {
        implementation("io.ktor:ktor-client-cio:KTOR_VERSION")
    }
}
val androidMain by getting {
    dependsOn(jvmMain)
}
val jsMain by getting {
    dependencies {
        implementation("io.ktor:ktor-client-js:KTOR_VERSION")
    }
}
val iosMain by getting {
    dependencies {
        implementation("io.ktor:ktor-client-darwin:KTOR_VERSION")
    }
}

Add KotlinX Serialization (required for PostgREST and Realtime serialization)#

Add the serialization plugin

plugins {
    kotlin("plugin.serialization") version "KOTLIN_VERSION"
}

Now you can create serializable classes in your project:

@Serializable
data class Message(
    val id: Int,
    val content: String,
    @SerialName("author_id")
    val authorId: String
)

And use them in your Supabase queries:

val messages = client.postgrest["messages"].select().decodeList<Message>()

Initializing

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.


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

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

val city = client.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.

val city = City(name = "The Shire", countryId = 554)
client.postgrest["cities"].insert(city, returning = Returning.MINIMAL) //returning defaul 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.

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

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.

val toUpsert = Message(id = 3, message = "foo", username = "supabot")
client.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.

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

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.

client.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:

eq("country_id", 1)

And using a class property:

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.


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

Column is equal to a value

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


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

Column is not equal to a value

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


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

Column is greater than a value

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


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

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.


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

Column is less than a value

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


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

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.


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

Column matches a pattern

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


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

Column matches a case-insensitive pattern

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


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

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.


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

Column is in an array

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


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

Column contains every element in a value


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

Greater than a range

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


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

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.


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

Less than a range

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


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

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.


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

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.


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

With a common element

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


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

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.

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

Match at least one filter

Finds all rows satisfying at least one of the filters.


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

Match the filter

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


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

Order the results

Order the query result by column.


client.postgrest["countries"].select(columns = Columns.list("id", "name")) {
   order(column = "id", order = Order.ASCENDING)
}

Limit the number of rows returned

Limit the query result by count.


client.postgrest["countries"].select {
    limit(count = 20)
}

Limit the query to a range

Limit the query result by from and to inclusively.


client.postgrest["countries"].select {
    range(1L..5L)
}

Overview

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

val client = createSupabaseClient(supabaseURL = "https://xyzcompany.supabase.co'", supabaseKey = "public-anon-key") { ... }
val gotrue = client.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 null and you will be logged in instead.
    • If Confirm email is disabled, the return value is the user and you won't be logged in automatically.
  • 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.
  • supabase-kt has default platform implementations:
    • On JVM, you can currently only verify a sign up through the token. To send the token, rather than a redirect url, you have to change {{ .ConfirmationURL }} in your sign up email to {{ .Token }}
    • deep links (Android),
    • url schemes (IOS)
      • To enable deeplinking/url scheme support on Android/IOS set the host and the scheme in the GoTrue Config and call client.handleDeeplinks(intent) (Android) and client.handleDeeplinks(url) (IOS) on startup
    • the website origin (JS)
  • 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.

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

val user = client.gotrue.signUpWith(Phone) {
    phoneNumber = "+4912345679" 
    password = "example-password"
}

Sign in a user

Logs in an existing user.

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

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

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.
  • supabase-kt has default platform implementations:
    • On JVM, you can currently only verify a OTP through the token. To send the token, rather than a redirect url, you have to change {{ .ConfirmationURL }} in your OTP email to {{ .Token }}
    • deep links (Android),
    • url schemes (IOS)
      • To enable deeplinking/url scheme support on Android/IOS set the host and the scheme in the GoTrue Config and call client.handleDeeplinks(intent) (Android) and client.handleDeeplinks(url) (IOS) on startup
    • the website origin (JS)
  • 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 }}.

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

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.
  • supabase-kt has default platform implementations:
    • HTTP Callback Server (JVM),
    • deep links (Android),
    • url schemes (IOS)
      • To enable deeplinking/url scheme support on Android/IOS set the host and the scheme in the GoTrue Config and call client.handleDeeplinks(intent) (Android) and client.handleDeeplinks(url) (IOS) on startup
    • the website origin (JS)

client.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.
  • supabase-kt has default platform implementations:
    • HTTP Callback Server (JVM),
    • deep links (Android),
    • url schemes (IOS)
      • To enable deeplinking/url scheme support on Android/IOS set the host and the scheme in the GoTrue Config and call client.handleDeeplinks(intent) (Android) and client.handleDeeplinks(url) (IOS) on startup
    • the website origin (JS)

  // You can extract the user's email domain and use it to trigger the
  // authentication flow with the correct identity provider.

  client.gotrue.loginWith(SSO.withDomain("company.com"))
  
  //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.

client.gotrue.logout()

Verify and log in through OTP

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


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


val session = client.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.

val session = client.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.

val user = client.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.

val user = client.gotrue.modifyUser(Email) {
   email = "newEmail@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.

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

Listen to auth events

Listen to session changes.


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

Enroll a factor

Enrolls a new factor.


val factor = client.gotrue.mfa.enroll(factorType = 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.
val (id, type, qrCode) = factor.data //qrCode is a svg as a string
val (factorId, factorType, _) = factor

Create a challenge

Creates a challenge for a factor.


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

Verify a challenge

Verifies a challenge for a factor.


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

Create and verify a challenge

Creates and verifies a challenge for a factor.


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

Unenroll a factor

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


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

val (current, next) = client.gotrue.mfa.getAuthenticatorAssuranceLevel()

Auth Admin

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

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

// Access auth admin api
val adminGoTrueClient = client.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.

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

List all users

Retrieves a list of users.

  • Defaults to return 50 users per page.

val users = client.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.

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

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.

client.gotrue.admin.deleteUser(uid = "uid")

Send an email invite link

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


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

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().
  • 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 redirectUrl 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 modifyUser():
    client.gotrue.modifyUser(Email) {
        password = "1234567"
    }
    

client.gotrue.sendRecoveryEmail(email = "example@email.com")

Generates email links and OTPs to be sent via a custom email provider.

Update a user

Updates the user data.


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

List all factors for a user

Lists all factors associated to a user.


const factors = client.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.


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

Invoke a 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.

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

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

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

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

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

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

val bucket = client.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

val bucke = client.storage.retrieveBuckets()

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

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

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

val bucket = client.storage["avatars"]
bucket.upload("myIcon.png", byteArray, upsert = false)
//on JVM you can use java.io.File
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

val bucket = client.storage["avatars"]
val bytes = bucket.downloadAuthenticated("test.png")
//or on JVM:
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

val bucket = client.storage["avatars"]
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

val bucket = client.storage["avatars"]
bucket.update("myIcon.png", byteArray, upsert = false)
//on JVM you can use java.io.File
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

val bucket = client.storage["avatars"]
bucket.move("icon1.png", "icon2.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

val bucket = client.storage["avatars"]
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

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