Halt unauthenticated connection in LiveView

How to halt and redirect if the user is not authenticated but tries to access the live route?
The second mount function gives invalid result returned error.

  @impl true
  def mount(_params, %{"current_user_id" => _current_user_id}, socket) do
    {:ok, socket}
  end

  @impl true
  def mount(_params, _session, _socket) do
    {:error, :unauthorized}
  end

mount callback return signature can only be {:ok, Socket.t()} or {:ok, Socket.t(), keyword()}.

You should make use of redirect to annotate the socket for redirection.

Also, check the Security considerations of the LiveView model. It addresses exactly your question in its examples.

2 Likes