supabase-csharp

repository·master·Indexed 20 days ago

https://github.com/supabase-community/supabase-csharp

A comprehensive C# client library for the Supabase ecosystem. It provides integration with Postgrest (Database), Gotrue (Auth), Storage, Edge Functions, and Realtime. The library supports strongly typed database queries via From<TModel>(), PostgreSQL RPC function invocation, and OpenTelemetry observability for tracing and metrics.

Tokens
2.3K
Snippets
6
Records
15
Agent score
72%

What's inside supabase-csharp

  1. Quickstart: Initialize the Supabase client

    master

    To use Supabase in your C# project, follow these steps:

    1. Create a new project in the Supabase Admin Panel.
    2. Retrieve your Supabase URL and Supabase Public Key from the Admin Panel (Settings -> API Keys).
    3. Initialize the client using these credentials.

    Security Warning: Some APIs (like user administration or bypassing database roles) require the service_key instead of the public_key. Never expose the service_key on the client side. If your application needs both a service account and a public/user account, use two separate client instances.

  2. Configure OpenTelemetry observability

    master

    The Supabase clients emit traces and metrics through System.Diagnostics. You can wire these into OpenTelemetry without adding extra dependencies to the Supabase library itself. Emission is zero-cost when no listeners are active.

    To instrument the clients, use SupabaseDiagnostics.SourceNames to retrieve the names of all instrumented clients (Auth, Postgrest, Functions, and Storage). Note that Realtime is not yet instrumented.

    To ensure privacy, URLs are recorded without query strings, and no tokens, credentials, or payloads are included in tags.

    using OpenTelemetry.Metrics;
    using OpenTelemetry.Trace;
    using Supabase;
    
    // Requires OpenTelemetry.Extensions.Hosting and an exporter (e.g., OTLP) in your app.
    builder.Services.AddOpenTelemetry()
        .WithTracing(tracing => tracing
            .AddSource(SupabaseDiagnostics.SourceNames.ToArray())
            .AddOtlpExporter())
        .WithMetrics(metrics => metrics
            .AddMeter(SupabaseDiagnostics.SourceNames.ToArray())
            .AddOtlpExporter());
  3. Migrating from v0.16.x to v1.0.0

    master

    If you are upgrading from version 0.16.x to v1.0.0, note the following breaking changes:

    • The NuGet package name has changed from supabase-csharp to Supabase.
    • The assembly name has changed from supabase to Supabase.
    • Namespace Change: Most APIs have moved from the Postgrest namespace to the Supabase.Postgrest namespace. You will need to update your using directives accordingly.
  4. Initialize the Supabase Client

    master

    To use Supabase in your C# application, create an instance of the Client class using your project's URL and API key. You can optionally provide SupabaseOptions to configure behavior like session persistence or custom headers.

    After instantiation, call InitializeAsync() to retrieve the existing session from the session handler and, if AutoConnectRealtime is enabled in your options, establish the Realtime connection.

    var options = new SupabaseOptions
    {
        AutoConnectRealtime = true
    };
    
    var supabase = new Client("https://your-project.supabase.co", "your-anon-key", options);
    await supabase.InitializeAsync();
  5. Troubleshoot Blazor WebAssembly integrity errors

    master

    If you encounter an error stating Failed to find a valid digest in the 'integrity' attribute for resources like blazor.boot.json, it is typically caused by old files being stored in the browser cache.

    Solution:

    1. Open the browser developer tools.
    2. Use the Clear Site Data (or Clear Cache) button in the Application/Storage tab.
    3. Perform a hard refresh using Ctrl + F5 (or Cmd + Shift + R on Mac).

    Note: A standard Ctrl + F5 may not be sufficient to clear the service worker cache; you must explicitly clear the site data/cache first.

  6. Handle expired JWT errors in Blazor WebAssembly

    master

    When an application is opened after a session has expired, attempting to call SignOut() or fetch data may result in a Supabase.Gotrue.RequestException with a 401 status code.

    Error Pattern: Supabase.Gotrue.RequestException: {"code":401,"msg":"invalid JWT: unable to parse or verify signature, token is expired by ..."}

    This occurs because the client attempts to use an expired token for an authenticated request. Developers should implement logic to detect expired tokens and redirect the user to the login flow or refresh the session before making requests.

  7. Configure the GoTrue (gotrue) auth service

    master

    The gotrue service handles authentication and user management. Key configuration environment variables include:

    • GOTRUE_JWT_SECRET: The secret used for signing and verifying JWTs.
    • GOTRUE_JWT_EXP: JWT expiration time in seconds.
    • GOTRUE_DISABLE_SIGNUP: Set to 'true' to disable new user registrations.
    • GOTRUE_MAILER_AUTOCONFIRM: Set to 'true' to automatically confirm email addresses (useful for local development).
    • GOTRUE_API_HOST: The host the service binds to (e.g., 0.0.0.0).
    • API_EXTERNAL_URL: The external URL used for generating links.
    • GOTRUE_SITE_URL: The base URL for the application.
    • DATABASE_URL: The connection string for the PostgreSQL database.
    • GOTRUE_OPERATOR_TOKEN: A token used for administrative operations.
  8. Configure the Database (db) service

    master

    The db service runs the PostgreSQL instance.

    • Ports: Exposed on 5432.
    • Initialization: Any SQL files placed in ./SupabaseTests/db will be executed in the /docker-entrypoint-initdb.d/ directory upon container creation.
    • Environment: POSTGRES_PASSWORD defines the default password (set to postgres in this configuration).
  9. Configure the Postgrest (rest) service

    master

    The rest service uses Postgrest to provide a RESTful API over your PostgreSQL database. Key configuration environment variables include:

    • PGRST_DB_URI: The connection URI for the database (e.g., postgres://postgres:postgres@db:5432/postgres).
    • PGRST_DB_SCHEMA: A comma-separated list of schemas to expose (e.g., public,storage).
    • PGRST_DB_EXTRA_SEARCH_PATH: Additional schemas to include in the search path (e.g., public,storage,extensions).
    • PGRST_DB_ANON_ROLE: The database role used for anonymous requests.
    • PGRST_JWT_SECRET: The secret used to validate JWTs.
  10. Configure the Realtime service

    master

    The realtime service enables real-time capabilities via WebSockets. Key configuration environment variables include:

    • DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, DB_NAME: Database connection credentials.
    • DB_ENC_KEY: The encryption key for the database.
    • API_JWT_SECRET: The secret used to validate JWTs for real-time connections.
    • DB_AFTER_CONNECT_QUERY: A SQL command to run immediately after connecting (e.g., SET search_path TO _realtime).
    • SECRET_KEY_BASE: A long, secure string used for internal cryptographic operations.
  11. Access Supabase sub-clients

    master

    The Client class acts as a central coordinator for all Supabase services. You can access specific service clients through the following properties:

    • Auth: Manage user authentication and sessions (IGotrueClient<User, Session>).
    • Postgrest: Perform strongly typed REST interactions with your database (IPostgrestClient).
    • Realtime: Listen to real-time database changes (IRealtimeClient<RealtimeSocket, RealtimeChannel>).
    • Storage: Manage user-generated content like files and buckets (IStorageClient<Bucket, FileObject>).
    • Functions: Invoke Supabase Edge Functions (IFunctionsClient).