DEV Community

Will Ceolin
Will Ceolin

Posted on

How to get the host from a LiveView Socket

First, you need to allow the WebSocket to display the URI. You can do it by editing your endpoint.ex file:

socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [:uri, session: @session_options]]
Enter fullscreen mode Exit fullscreen mode

In the example above, we added :uri the connect_info websocket option.

Now, we can create a mount hook to get access to the host value. In the example below, we'll add the host to our socket assigns, so we can use it in our LiveView with socket.assigns.host:

# host_plug.ex
def on_mount(:add_host, params, _session, socket) do
  %URI{host: host} = Phoenix.LiveView.get_connect_info(socket, :uri)

  socket = Phoenix.Component.assign(socket, host: host)

  {:cont, socket}
end
Enter fullscreen mode Exit fullscreen mode

Now, you need to add this mount hook to our live_session in our router.ex file:

scope "/", MyAppWeb do
  pipe_through [:browser]

  live_session :my_routes,
    on_mount: [{MyAppWeb.HostHook, :add_host}] do
    live "/", HomeLive
  end
end
Enter fullscreen mode Exit fullscreen mode

That's it! Now we can get the host in our LiveView by using socket.assigns.host.


Note: If you're getting an error like this: ** (MatchError) no match of right hand side value: nil, it might mean that you forgot to add :uri to your connect_info as I mentioned on the first step.

Top comments (0)