Phoenix LiveView and PostHog
PostHog is an all-in-one platform for usage tracking - including product analytics, feature flags, session replays and surveys.
Integrating PostHog with Phoenix LiveView is relatively straightforward, if you follow the generic Javascript Web setup instructions. (Note the posthog hex.pm package is a HTTP client wrapper to capture events, and is not intended for a LiveView browser session)
One LiveView-specific change
The only change required to integrate with LiveView is register an event handler to (manually) capture $pageview
events when the LiveView session migrates to a new page; PostHog does not watch the browser history for changes automatically.
We can do this via adding an event listener for the phx:navigate
event:
1window.addEventListener("phx:navigate", ({ detail: { href } }) =>2 posthog.capture('$pageview', {3 '$current_url': href4 })5 );
This phx:navigate
event is triggered any time that the browser’s URL bar is programatically changed by Phoenix or the user, according to the documentation.