Supabase Rust Client
A comprehensive, production-ready Rust client library for Supabase. This library provides a clean, type-safe, and efficient interface to interact with all Supabase services.
✨ Features
- 🔐 Authentication: Full auth support including MFA, OAuth, Phone Auth, Magic Links, Anonymous Sign-in, and Advanced Token Management
- 💾 Session Management: Cross-tab Sync, Platform Storage, Session Encryption, Session Events
- 🗄️ Database: Advanced Queries, Raw SQL, and Type-safe PostgREST operations
- 📁 Storage: File operations with Resumable Uploads, Advanced Metadata, Storage Policies, and Real-time Events
- 📡 Realtime: WebSocket subscriptions with Presence System, Broadcast Messages, Advanced Filters, and Connection Pooling
- ⚡ Cross-Platform: Full Native (Tokio) and WebAssembly (WASM) support
- 🛡️ Type Safety: Full Rust type system integration
- 🔧 Well Tested: 65+ comprehensive tests
📦 Installation
Add this to your Cargo.toml
:
[]
= "0.4.2"
= { = "1.0", = ["full"] }
Or use cargo to add it:
🏃 Quick Start
use *;
async
📖 Usage Guide
Authentication
use *;
let client = new?;
// Sign up new user
let response = client
.auth
.sign_up_with_email_and_password
.await?;
// Sign in existing user
let response = client
.auth
.sign_in_with_email_and_password
.await?;
// Update user profile
let response = client
.auth
.update_user
.await?;
// Sign out
client.auth.sign_out.await?;
Multi-Factor Authentication (MFA)
use *;
let client = new?;
// Setup TOTP (Google Authenticator, Authy, etc.)
let totp_setup = client
.auth
.setup_totp
.await?;
println!;
println!;
println!;
// Setup SMS MFA with international phone number
let sms_factor = client
.auth
.setup_sms_mfa
.await?;
// Create MFA challenge
let challenge = client
.auth
.create_mfa_challenge
.await?;
// Verify with TOTP code from authenticator app
let auth_response = client
.auth
.verify_mfa_challenge
.await?;
// List configured MFA factors
let factors = client.auth.list_mfa_factors.await?;
for factor in factors
Advanced Token Management
// Check if token needs refresh with 5-minute buffer
if client.auth.needs_refresh_with_buffer?
// Get detailed token information
if let Some = client.auth.get_token_metadata?
// Validate token locally (no API call)
let is_valid = client.auth.validate_token_local?;
println!;
Session Management
use ;
// Create session manager with default storage
let storage_backend = create_default_storage?;
let config = SessionManagerConfig ;
let session_manager = new;
session_manager.initialize.await?;
// Store session with cross-tab sync
let session_id = session_manager.store_session.await?;
println!;
// Set up session event listener
let listener_id = session_manager.on_session_event;
// List all active sessions
let sessions = session_manager.list_sessions.await?;
println!;
// Session will automatically sync across browser tabs/windows
// and persist according to platform (localStorage, filesystem, etc.)
Database Operations
use *;
use ;
let client = new?;
// SELECT with filters and ordering
let posts = client
.database
.from
.select
.eq
.gt
.order
.limit
.
.await?;
// INSERT new record
let new_post = Post ;
let inserted = client
.database
.insert
.values?
.returning
.
.await?;
// UPDATE records
let update_data = json!;
let updated = client
.database
.update
.set?
.eq
.returning
.
.await?;
// DELETE records
let deleted = client
.database
.delete
.eq
.returning
.
.await?;
// Call RPC function
let result = client
.database
.rpc
.await?;
Storage Operations
use *;
use Bytes;
let client = new?;
// Create bucket
let bucket = client
.storage
.create_bucket
.await?;
// Upload file
let file_content = from;
let upload_result = client
.storage
.upload
.await?;
// Upload with options
let options = FileOptions ;
let upload_result = client
.storage
.upload
.await?;
// Download file
let file_data = client
.storage
.download
.await?;
// Get public URL
let public_url = client
.storage
.get_public_url;
// Create signed URL
let signed_url = client
.storage
.create_signed_url
.await?;
// List files
let files = client
.storage
.list
.await?;
Realtime Subscriptions
use *;
let client = new?;
let realtime = client.realtime;
// Connect to realtime
realtime.connect.await?;
// Subscribe to all changes on a table
let subscription_id = realtime
.channel
.table
.subscribe
.await?;
// Subscribe to specific events
let insert_subscription = realtime
.channel
.table
.event
.subscribe
.await?;
// Subscribe with filters
let filtered_subscription = realtime
.channel
.table
.filter
.subscribe
.await?;
// Unsubscribe
realtime.unsubscribe.await?;
🔧 Development
This project uses Nix for reproducible development environments.
Prerequisites
- Nix package manager with flakes enabled
- just command runner (included in Nix environment)
Setup
# Enter the development environment
# Or run commands directly
Available Commands
# Show all available commands
# Format code
# Run linter
# Run tests
# Build project
# Run all checks (format, lint, test, build)
# Start local Supabase for testing
# Run examples
Project Structure
supabase-lib-rs/
├── src/
│ ├── lib.rs # Library entry point
│ ├── client.rs # Main Supabase client
│ ├── auth.rs # Authentication module
│ ├── database.rs # Database operations
│ ├── storage.rs # File storage
│ ├── realtime.rs # WebSocket subscriptions
│ ├── error.rs # Error handling
│ └── types.rs # Common types and configurations
├── examples/ # Usage examples
├── tests/ # Integration tests
├── flake.nix # Nix development environment
├── justfile # Command runner configuration
└── CLAUDE.md # Development guidelines
🧪 Testing
This project has a comprehensive testing system with multiple levels of testing:
Unit Tests
# Run unit tests only
# Run with documentation tests
Integration & E2E Tests
# Start local Supabase (requires Docker/Podman)
# Run integration tests
# Run all tests (unit + doc + integration)
Docker/Podman Setup
The project includes a complete local Supabase setup using Docker Compose:
# Start all Supabase services
# Check status
# View logs
# Stop services
# Clean up data
Services provided:
- 🌐 Studio: http://localhost:54323 (Web UI)
- 🔗 API: http://localhost:54321 (REST + Auth + Realtime)
- 🗄️ Database: localhost:54322 (PostgreSQL)
- 📁 Storage: File storage with image processing
- ⚡ Functions: Edge functions runtime
Test Categories
- Unit Tests - Fast, isolated component tests
- Integration Tests - Test individual modules against real Supabase
- E2E Tests - Full workflow scenarios
- Doc Tests - Ensure documentation examples work
All integration tests automatically skip if Supabase is not available, making them safe for CI/CD.
🚧 Current Limitations
While this library provides comprehensive Supabase functionality, some advanced features are planned for future releases:
Authentication
- OAuth Providers: Google, GitHub, Discord, Apple, etc. (planned for v0.3.1)
- Phone Authentication: SMS OTP and phone number sign-in (planned for v0.3.1)
- Multi-Factor Authentication (MFA): TOTP and SMS-based 2FA (planned for v0.4.0)
- Auth Events:
onAuthStateChange
event listeners (planned for v0.3.1) - Anonymous Sign-in: Temporary anonymous user sessions (planned for v0.3.1)
Database
- ✅ Logical Operators: Complex
and()
,or()
,not()
query logic (Added in v0.3.0) - ✅ Query Joins:
inner_join()
,left_join()
with aliases (Added in v0.3.0) - ✅ Batch Operations:
upsert()
,bulk_insert()
,bulk_upsert()
(Added in v0.3.0) - ✅ Raw SQL Support:
raw_sql()
,prepared_statement()
,count_query()
(Added in v0.3.0) - ✅ Database Transactions: Full transaction support with builder pattern (Added in v0.3.0)
- Full-Text Search:
textSearch()
and advanced search operators (planned for v0.4.0) - Query Analysis:
explain()
and CSV export functionality (planned for v0.4.0)
Missing Modules
Edge Functions:✅ Added in v0.3.0 🚀 Enhanced in v0.4.2functions.invoke()
for serverless functions- Management API: Project management and admin operations (planned for v0.4.0)
Workarounds
Most limitations can be worked around:
// Instead of OAuth, use magic links or email/password
let auth_response = client.auth
.sign_up_with_email_and_password
.await?;
// Instead of logical operators, use multiple queries or raw SQL
let result = client.database
.rpc
.await?;
// Instead of Edge Functions, use database RPC functions
let function_result = client.database
.rpc
.await?;
The library currently provides ~95% of core Supabase functionality and covers all common use cases for production applications.
🎉 What's New in v0.3.0
🔗 Advanced Database Operations
v0.3.0 brings powerful database enhancements that make complex queries simple:
// ✨ Logical operators for complex filtering
let active_adults = client.database
.from
.select
.and
.execute
.await?;
// 🔗 Query joins with related data
let posts_with_authors = client.database
.from
.select
.inner_join_as
.left_join
.execute
.await?;
// 📦 Bulk operations for efficiency
let users = client.database
.bulk_upsert
.await?;
// ⚡ Database transactions
let result = client.database
.begin_transaction
.insert
.update
.delete
.commit
.await?;
📚 Examples
The examples/
directory contains comprehensive examples:
basic_usage.rs
- Overview of all featuresauth_example.rs
- Authentication flowsdatabase_example.rs
- Database operationsstorage_example.rs
- File storage operationsrealtime_example.rs
- WebSocket subscriptions
Run examples with:
🌐 WebAssembly (WASM) Support
This library provides full WebAssembly support for web applications! You can use it with frameworks like Dioxus, Yew, or any WASM-based Rust web framework.
WASM Features
- ✅ Full API compatibility - Same API works on both native and WASM
- ✅ HTTP client - Uses browser's fetch API automatically
- ✅ Authentication - Complete auth flow support
- ✅ Database - All CRUD operations and query builder
- ✅ Storage - File upload/download (simplified for WASM)
- ✅ Realtime - WebSocket subscriptions via browser WebSocket API
Building for WASM
# Add WASM target
# Build for WASM
# Build example for WASM
WASM Example
use ;
use *;
pub async
Integration with Web Frameworks
Dioxus:
use *;
use Client;
Yew:
use *;
use Client;
⚙️ Configuration
Environment Variables
The library can be configured using environment variables. Copy .env.example
to .env
and fill in your actual values:
Required variables:
SUPABASE_URL
- Your Supabase project URLSUPABASE_ANON_KEY
- Your Supabase anonymous key
Optional variables:
SUPABASE_SERVICE_ROLE_KEY
- Service role key for admin operationsRUST_LOG
- Log level (debug, info, warn, error)RUST_BACKTRACE
- Enable backtrace (0, 1, full)
Getting Your Supabase Keys
- Go to your Supabase Dashboard
- Select your project
- Navigate to Settings > API
- Copy the keys:
- Project URL →
SUPABASE_URL
- anon public →
SUPABASE_ANON_KEY
- service_role →
SUPABASE_SERVICE_ROLE_KEY
(keep this secret!)
- Project URL →
Custom Configuration
use ;
let config = SupabaseConfig ;
let client = new_with_config?;
🤝 Contributing
We welcome contributions! Please see our Contributing Guidelines for details.
Development Workflow
- Fork the repository
- Create a feature branch
- Make your changes following the coding standards
- Run the full test suite:
just check
- Submit a pull request
Code Standards
- Follow the existing code style
- Add tests for new features
- Update documentation as needed
- Ensure all checks pass:
just check
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🔗 Links
🙏 Acknowledgments
- Supabase for providing an amazing backend platform
- The Rust community for excellent crates and tooling
- Contributors who help improve this library
Made with ❤️ for the Rust and Supabase communities