Supabase Elixir SDK

repository·main·Indexed 41 days ago

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

A community-driven SDK for interacting with Supabase services from Elixir applications. It provides a central Supabase.Client to coordinate specialized clients for PostgREST, Storage, Auth, Functions, and Realtime. The SDK includes packages such as supabase_potion, supabase_storage, supabase_auth, supabase_postgrest, supabase_functions, and supabase_realtime.

Tokens
12.9K
Snippets
42
Records
55
Agent score
100%

What's inside Supabase Elixir

  1. Overview of the Supabase Elixir Ecosystem

    main

    The Supabase Elixir ecosystem consists of several specialized libraries designed to integrate Elixir applications with Supabase services:

    • supabase-ex: The primary client for interacting with Supabase APIs, providing high-level configuration for HTTP clients.
    • postgrest-ex: A library for interacting with PostgREST, featuring lazy query/filter builders and Ecto integration for parsing JSON responses into schemas.
    • storage-ex: Handles Supabase Storage operations, including full CRUD for buckets and streaming support for large file uploads/downloads.
    • gotrue-ex: Manages authentication (GoTrue), supporting OAuth, OTP, email/password, SSO, and anonymous sign-in. It includes native support for Phoenix Plug and LiveView hooks.
  2. Core Technologies used in Supabase Phoenix User Management

    main

    This example integrates several components to provide a full user management experience:

  3. Understand the Supabase.Client struct

    main

    A Supabase.Client is the central entity used to interact with Supabase services. It holds connection details, database schema information, global headers, and authentication settings.

    Key fields:

    • name: An atom identifying the client.
    • conn: Contains base_url, api_key, and access_token.
    • db: Contains the schema (defaults to "public").
    • global: Contains headers.
    • auth: Configuration for authentication, including auto_refresh_token, flow_type, and persist_session.
    %Supabase.Client{
      name: MyClient,
      conn: %{
        base_url: "https://<app-name>.supabase.io",
        api_key: "<supabase-api-key>",
        access_token: "<supabase-access-token>"
      },
      db: %Supabase.Client.Db{
        schema: "public"
      },
      global: %Supabase.Client.Global{
        headers: %{}
      },
      auth: %Supabase.Client.Auth{
        auto_refresh_token: true,
        debug: false,
        detect_session_in_url: true,
        flow_type: :implicit,
        persist_session: true,
        storage: nil,
        storage_key: "sb-<host>-auth-token"
      }
    }
  4. Understand the Supabase.Client structure

    main

    A Supabase.Client is the central abstraction used to interact with Supabase services. It contains connection details, database schema information, global headers, and authentication settings.

    Key fields include:

    • name: The module name used to identify the client.
    • conn: Contains base_url, api_key, and access_token.
    • db: Configuration for the database, such as schema (defaults to "public").
    • global: Global headers for requests.
    • auth: Authentication settings including auto_refresh_token, detect_session_in_url, and storage_key.
    # fields with sensitive values are filtered when inspected
    %Supabase.Client{
      name: MyClient,
      conn: %{
        base_url: "https://<app-name>.supabase.io",
        api_key: "<supabase-api-key>",
        access_token: "<supabase-access-token>"
      },
      db: %Supabase.Client.Db{
        schema: "public"
      },
      global: %Supabase.Client.Global{
        headers: %{}
      },
      auth: %Supabase.Client.Auth{
        auto_refresh_token: true,
        debug: false,
        detect_session_in_url: true,
        flow_type: :implicit,
        persist_session: true,
        storage: nil,
        storage_key: "sb-<host>-auth-token"
      }
    }
  5. Use gotrue-ex for authentication and user management

    main

    The gotrue-ex library provides comprehensive user management including sign-up, password resets, email invitations, and admin APIs.

    Supported Auth Methods:

    • OAuth
    • OTP
    • Email/Password
    • ID Token
    • SSO
    • Anonymous Sign In

    Integrations:

    • Plug Support: Can be used as middleware in Phoenix applications.
    • Phoenix.LiveView Hooks: Provides out-of-the-box support for LiveView environments.
  6. Set up Supabase Postgres connection in Phoenix

    main

    To connect a Phoenix application to a Supabase Postgres database, you must configure your database connection string or parameters.

    Production Environment

    In production, set the DATABASE_URL environment variable in your config/runtime.exs. Use the URI provided in the Supabase dashboard under Database Settings, ensuring Use connection pooling is checked and Session mode is selected.

    Local Development

    For local development using the supabase-cli, modify config/dev.exs to use the local Postgres credentials (typically port 54322).

    # config/dev.exs
    
    import Config
    
    config :blog, Blog.Repo,
      hostname: "localhost",
      port: 54322, # default supabase-cli postgres port
      username: "postgres",
      password: "postgres",
      database: "postgres"
  7. Configure Database Schema for User Profiles and Storage

    main

    The user management example requires a specific database schema to handle user profiles and avatar storage via Row Level Security (RLS).

    Profiles Table

    Creates a profiles table linked to Supabase Auth. It includes policies allowing anyone to view profiles, but only the owner to insert or update their own profile.

    Storage Buckets

    Creates an avatars bucket in Supabase Storage with policies allowing public read access and allowing any user to upload images to that specific bucket.

    Run the following SQL in your Supabase SQL Editor to set up the required schema:

    -- Create a table for public "profiles"
    create table profiles (
      id uuid primary key,
      user_id uuid not null,
      username text,
      website text,
      avatar_url text,
      inserted_at timestamp with time zone default timezone('utc'::text, now()) not null,
      updated_at timestamp with time zone default timezone('utc'::text, now()) not null
    );
    
    alter table profiles enable row level security;
    
    create policy "Public profiles are viewable by everyone."
      on profiles for select
      using ( true );
    
    create policy "Users can insert their own profile."
      on profiles for insert
      with check ( auth.uid() = user_id );
    
    create policy "Users can update own profile."
      on profiles for update
      using ( auth.uid() = user_id );
    
    -- Set up Storage
    insert into storage.buckets (id, name)
    values ('avatars', 'avatars');
    
    create policy "Avatar images are publicly accessible."
      on storage.objects for select
      using ( bucket_id = 'avatars' );
    
    create policy "Anyone can upload an avatar."
      on storage.objects for insert
      with check ( bucket_id = 'avatars' );
  8. Configure and initialize the Supabase client

    main

    To use supabase-ex, you must first configure the base URL and API key in your config.exs or runtime.exs. Once configured, you initialize a client using Supabase.init_client/2, which returns a PID that can be used in subsequent API calls.

    # 1. Configure in config/config.exs
    import Config
    
    config :supabase_potion,
      supabase_base_url: System.get_env("SUPABASE_URL"),
      supabase_api_key: System.get_env("SUPABASE_KEY")
    
    # 2. Initialize the client in your application
    {:ok, client_pid} = Supabase.init_client(MyClient, additional_config)
  9. Setup Supabase Phoenix User Management

    main

    To run the Supabase Phoenix User Management example, you must first configure your Supabase project credentials as environment variables and initialize the local Phoenix environment.

    1. Configure Environment Variables: Set your Supabase project URL and the anon API key.
    2. Initialize Project: Run mix setup to install dependencies and prepare the database.
    3. Start Server: Run mix phx.server to launch the application.

    The application will be available at http://localhost:4000.

    export SUPABASE_URL=https://your-project.supabase.co
    export SUPABASE_KEY=your-anon-key
    
    mix setup
    mix phx.server