Skip to main content

Crate rust_supabase_sdk

Crate rust_supabase_sdk 

Source
Expand description

An async Rust client for Supabase.

Mirrors the supabase-js surface area where it makes sense and pushes Rust-native ergonomics elsewhere: a chainable PostgREST builder, typed row queries via from_row, a pluggable SessionStore for auth persistence, retry/backoff for 429s, and feature-gated realtime + edge functions.

§Quickstart — string-typed (zero setup)

use rust_supabase_sdk::SupabaseClient;

#[tokio::main]
async fn main() -> rust_supabase_sdk::Result<()> {
    let client = SupabaseClient::new(
        std::env::var("SUPABASE_URL").unwrap_or_default(),
        std::env::var("SUPABASE_API_KEY").unwrap_or_default(),
        None,
    );

    let rows: Vec<serde_json::Value> = client
        .from("countries")
        .select("id,name")
        .eq("region", "Europe")
        .order("name", true)
        .limit(10)
        .await?;

    for row in rows {
        println!("{row}");
    }
    Ok(())
}

§Type-safe queries — wrong column or value type fails to compile

Opt into the typed path whenever you want compile-time guarantees about column names and value types. Run cargo supabase gen types once to emit a Row struct + a Column<R, V> constants block per table, then:

let rows: Vec<Posts> = client.from_row::<Posts>()
    .eq(Posts::status, "published".to_string())
    .gt(Posts::view_count, 100i32)
    .is_null(Posts::archived)
    .execute()
    .await?;

Misuse becomes a compile error:

.eq(Users::id, "x")                  // ✗ wrong row type
.eq(Posts::view_count, "abc")        // ✗ view_count is i32, not &str
.is_null(Posts::status)              // ✗ status is NOT NULL
.like(Posts::view_count, "10%")      // ✗ like requires a string-typed column

Runtime cost is zero — Column<R, V> is a &'static str plus a phantom type. The typed and string-typed paths coexist on the same client; pick per query.

§Modules

  • postgrest — chainable query builder + typed row queries.
  • auth — sign-in (email / phone / OTP / OAuth / anonymous), recovery, admin user management, and the SessionStore trait.
  • storage — buckets, object CRUD, signed URLs, image transforms.
  • rpc — call Postgres functions.
  • functions — invoke Supabase Edge Functions (feature functions).
  • realtime — websocket subscriptions to postgres_changes, broadcast, and presence (feature realtime, off by default).

§Feature flags

FlagDefaultWhat it does
postgrestPostgREST query builder.
authSign-in flows, OAuth, admin user management.
storageBuckets, objects, signed URLs.
functionsEdge Functions invocation.
realtimeWebsocket subscriptions (opt-in).
rustlsTLS via rustls (default).
native-tlsOS-native TLS instead of rustls.

§Customizing the client

Use SupabaseClient::builder when you need a custom schema, retry policy, HTTP client, persistent session store, or extra headers:

use std::time::Duration;
use rust_supabase_sdk::{SupabaseClient, RetryConfig};

let client = SupabaseClient::builder("https://proj.supabase.co", "anon-key")
    .timeout(Duration::from_secs(30))
    .retry(RetryConfig::new(3, Duration::from_millis(100)))
    .user_agent("my-app/1.0")
    .schema("public")
    .build();

§Code generation

The companion cargo-supabase binary introspects a project’s PostgREST schema and emits, per table, a Row struct and a Column<R, V> constants block for the typed query path:

cargo install cargo-supabase
cargo supabase gen types --url $SUPABASE_URL --apikey $SUPABASE_SERVICE_ROLE_KEY \
    --output src/generated.rs

Re-run after any migration — schema drift becomes a compile error rather than a runtime decode failure.

§Examples

Worked examples for every major surface area live under examples/ in the repository.

Re-exports§

pub use auth::session_store::InMemorySessionStore;
pub use auth::session_store::SessionStore;
pub use auth::types::Identity;
pub use auth::types::Session;
pub use auth::types::User;
pub use auth::Auth;
pub use auth::AuthAdmin;
pub use error::AuthError;
pub use error::PostgrestError;
pub use error::Result;
pub use error::StorageError;
pub use error::SupabaseError;
pub use postgrest::Row;

Modules§

auth
Authentication & user management — modeled on supabase-js’s auth namespace.
error
Error types for the SDK.
functions
Supabase Edge Functions — invoke a deployed function by name.
postgrest
PostgREST query builder — the primary data API.
realtime
Supabase Realtime — WebSocket-based subscriptions for Postgres changes, broadcast, and presence.
rpc
storage
Supabase Storage — buckets and object operations.
universals

Structs§

ClientBuilder
Builder for customizing a SupabaseClient.
RetryConfig
Retry policy applied to transient (429/5xx) HTTP failures.
SupabaseClient
The main Supabase client. Cheap to clone — internal state is Arc-shared.

Functions§

generate_id
Generate a fresh v4 UUID as a String. Useful for client-side primary keys.