When building Phoenix LiveView applications, you may occasionally need to access the client’s IP address. LiveView does not expose this by default, but Phoenix provides a straightforward way to include it in the connection metadata and read it inside your LiveView.
Add :peer_data to your socket configuration
In your endpoint.ex, enable :peer_data inside the connect_info for the LiveView socket:
socket "/live", Phoenix.LiveView.Socket,
websocket: [connect_info: [:peer_data, session: @session_options]],
longpoll: [connect_info: [session: @session_options]]
This makes the remote IP address available to your LiveView process.
Read :peer_data inside the mount/3 function
Inside your LiveView module, you can fetch the connect info using get_connect_info/2:
peer_data = get_connect_info(socket, :peer_data)
This returns a map containing connection metadata, including the address field.
Extract the IP address
The address is a tuple such as {192, 168, 1, 10}. Convert it to a string:
ip = Enum.join(Tuple.to_list(peer_data.address), ".")
You can now store this IP in assigns or log it for monitoring and analytics.
Summary
By enabling :peer_data on the socket and reading it via get_connect_info/2, you can reliably access the client’s IP address inside any LiveView. This is useful for auditing, rate limiting, session tracking, and security-related features.
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.