Supabase.Auth.LiveView (supabase_auth v1.0.0)

View Source

Provides LiveView integrations for the Supabase Auth authentication in Elixir applications.

This module enables the seamless integration of authentication flows within Phoenix LiveView applications by leveraging the Supabase Auth SDK. It supports operations such as mounting current users, handling authenticated and unauthenticated states, and logging out users.

The Supabase client is provided to LiveView via socket assigns using the assign_supabase_client/2 helper, giving you full control over client lifecycle and enabling easy testing.

Configuration

The module requires some options to be passed:

  • endpoint: Your web app endpoint, used internally for broadcasting user disconnection events.
  • signed_in_path: The route to where the socket should be redirected to after authentication
  • not_authenticated_path: The route to where the socket should be redirected to if not authenticated

Usage

Define a module to be your LiveView Authentication entrypoint and use this module to inject the necessary functions:

defmodule MyAppWeb.UserAuth do
  use Supabase.Auth.LiveView,
    endpoint: MyAppWeb.Endpoint,
    signed_in_path: "/app",
    not_authenticated_path: "/login"
end

Then in your LiveView, assign the client in mount/3 before using on_mount callbacks:

defmodule MyAppWeb.DashboardLive do
  use MyAppWeb, :live_view

  def mount(_params, _session, socket) do
    client = Supabase.init_client!("https://myapp.supabase.co", "your-anon-key")
    socket = MyAppWeb.UserAuth.assign_supabase_client(socket, client)
    {:ok, socket}
  end
end

Or use the on_mount callback in your router's live_session:

live_session :authenticated,
  on_mount: [{MyAppWeb.UserAuth, :ensure_authenticated}] do
  live "/dashboard", DashboardLive
end

Check on_mount/4 for more detailed usage instructions on the available callbacks.