supabase-go

repository·main·Indexed 19 days ago

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

An isomorphic Go client for Supabase providing integrated access to Postgrest (database), GoTrue (authentication), Storage, and Edge Functions. It features support for CRUD operations via Postgrest, PostgreSQL function execution via Rpc, and authentication management including manual and automatic token refreshing.

Tokens
1.9K
Snippets
13
Records
13
Agent score
18%

What's inside supabase-go

  1. Initialize the Supabase client

    main

    You can initialize a client using supabase.NewClient. You will need your Supabase URL and API Key from your Supabase Admin Panel (Settings -> API Keys).

    Security Note: Some APIs require the service_key (e.g., for user administration or bypassing database roles). Never expose the service_key on the client side. If your application needs both service-level and user-level access, create two separate client instances.

    client, err := supabase.NewClient(API_URL, API_KEY, &supabase.ClientOptions{})
    if err != nil {
        fmt.Println("Failed to initalize the client: ", err)
    }
  2. Configure Supabase client options

    main

    You can pass a *supabase.ClientOptions struct to NewClient to customize the client behavior.

    Supported options:

    • Headers: A map[string]string for custom HTTP headers.
    • Schema: The database schema to use (defaults to "public").
    options := &supabase.ClientOptions{
        Headers: map[string]string{
            "X-Custom-Header": "custom-value",
        },
        Schema: "custom_schema", // defaults to "public"
    }
    
    client, err := supabase.NewClient(url, key, options)
  3. Manage authentication tokens

    main

    You can manage user sessions by manually refreshing tokens or enabling automatic background refreshes.

    Manual Refresh

    Use RefreshToken(refreshToken) to manually exchange a refresh token for a new session.

    Automatic Refresh

    Call EnableTokenAutoRefresh(session) to let the client handle token lifecycles. The client will:

    • Refresh tokens before they expire (at 75% of expiry time).
    • Retry failed refreshes with exponential backoff.
    • Update all service clients with the new tokens automatically.
    // Manual refresh
    newSession, err := client.RefreshToken(session.RefreshToken)
    
    // Automatic refresh
    client.EnableTokenAutoRefresh(session)
  4. Authenticate users with Email or Phone

    main

    The client uses an integrated GoTrue client for authentication. You can sign in users using either email/password or phone/password combinations.

    // Sign in with email and password
    session, err := client.SignInWithEmailPassword("user@example.com", "password")
    if err != nil {
        log.Fatal("Sign in failed:", err)
    }
    
    // Sign in with phone and password
    session, err := client.SignInWithPhonePassword("+1234567890", "password")
    if err != nil {
        log.Fatal("Sign in failed:", err)
    }
  5. Query data using the Postgrest integration

    main

    Use the .From(table) method to start a query against a specific table. The client integrates with postgrest-go for query building. For advanced querying, refer to the postgrest-go documentation.

    // Returns data, count, and error
    data, count, err := client.From("countries").Select("*", "exact", false).Execute()
  6. Enable automatic token refreshing

    main

    To maintain a continuous user session without manual intervention, call EnableTokenAutoRefresh(session types.Session). This starts a background goroutine that monitors the session's expiration and automatically refreshes the token using the RefreshToken method before it expires. It includes retry logic with exponential backoff.

    session, err := client.SignInWithEmailPassword(email, password)
    if err == nil {
        client.EnableTokenAutoRefresh(session)
    }
  7. Initialize a new Supabase client with NewClient

    main

    Use NewClient to create a new instance of the Supabase client. You must provide the Supabase url and your API key. You can optionally provide ClientOptions to specify a custom Schema (defaults to public) or additional Headers.

    import "github.com/supabase-community/supabase-go"
    
    client, err := supabase.NewClient(
        "https://your-project-id.supabase.co",
        "your-anon-key",
        &supabase.ClientOptions{
            Schema: "my_custom_schema",
            Headers: map[string]string{
                "X-Custom-Header": "value",
            },
        },
    )
    if err != nil {
        log.Fatal(err)
    }
  8. Authenticate users with Email or Phone

    main

    The client provides built-in methods for common authentication flows. When a successful session is returned, the client automatically updates its internal state with the new access token via UpdateAuthSession.

    // Sign in with email and password
    session, err := client.SignInWithEmailPassword("user@example.com", "password123")
    
    // Sign in with phone and password
    session, err := client.SignInWithPhonePassword("+123456789", "password123")
  9. Manually refresh an authentication token

    main

    If you need to refresh the session manually, use RefreshToken(refreshToken string). This method calls the Supabase Auth API and updates the client's internal headers and sub-clients (Storage, Functions, etc.) with the new access token.

    session, err := client.RefreshToken(oldRefreshToken)
  10. Execute RPC calls with Rpc

    main

    The Rpc(name, count string, rpcBody interface{}) method allows you to call PostgreSQL functions (Stored Procedures) directly. It wraps the underlying Postgrest RPC implementation.

    // name: function name, count: count parameter, rpcBody: arguments
    result := client.Rpc("my_function", "", map[string]interface{}{"param": "value"})
  11. Access database tables with From

    main

    The From(table string) method returns a postgrest.QueryBuilder for the specified table, allowing you to perform CRUD operations and complex queries via the Postgrest integration.

    // Returns a QueryBuilder for the 'users' table
    query := client.From("users")