DEV Community

Will Ceolin
Will Ceolin

Posted on

1

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.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay