PhoenixKitWebAnalytics.LiveHook (PhoenixKitWebAnalytics v0.2.0)

Copy Markdown View Source

Counts LiveView navigations as page views.

PhoenixKitWebAnalytics.Plug sees HTTP requests, which covers the first load of a LiveView page but not what happens afterwards: push_patch, push_navigate, and <.link patch={…}> change the URL over the socket without ever touching the router. Without this hook a LiveView-heavy app reports one page view per session and nothing else.

Attach it in the host's live_session:

live_session :public,
  on_mount: [{PhoenixKitWebAnalytics.LiveHook, :track_navigation}] do
  live "/", HomeLive
  live "/pricing", PricingLive
end

Requires connect_info on the socket

The hook needs the same two inputs the plug has — client IP and User-Agent — because they feed the daily visitor hash. Without them a LiveView navigation would hash to a different visitor than the page load that preceded it, inflating the visitor count. Rather than record data it knows to be wrong, the hook does nothing unless the endpoint provides them:

socket "/live", Phoenix.LiveView.Socket,
  websocket: [connect_info: [:peer_data, :user_agent, session: @session_options]]

Both keys must be listed. If either is missing the hook stays inert and only full page loads are counted — check this first if LiveView navigations aren't showing up.

Not double-counted

On a normal page load the dead render already produced a tracked HTTP response, so the hook ignores the handle_params that follows the connected mount. It tells that case apart from a push_navigate remount (which has no HTTP request behind it, and is counted) using LiveView's _mounts connect parameter.

Summary

Functions

on_mount callback. Use :track_navigation.

Functions

on_mount(atom, params, session, socket)

on_mount callback. Use :track_navigation.