Phoenix
Add OnyxMetric analytics to your Phoenix app
Phoenix renders every page inside the root layout, lib/my_app_web/components/layouts/root.html.heex, which owns <html> and <head>. Put the tag there and read the site ID from application config.
Copy your tracking snippet
In OnyxMetric, open your site's Site Settings and copy the tracking script. It looks like this:
<script src="https://app.onyxmetric.com/api/script.js?siteId=YOUR_SITE_ID" async></script>YOUR_SITE_ID is the numeric ID of your site.
Add the snippet to Phoenix
Configure the site ID
config/runtime.exs runs at boot, including inside a release, so read the environment variable there (replace :my_app with your OTP app):
config :my_app, :onyxmetric, site_id: System.get_env("ONYXMETRIC_SITE_ID")export ONYXMETRIC_SITE_ID=YOUR_SITE_IDExpose it to the layout
Templates in components/layouts/ are embedded in MyAppWeb.Layouts, so a function defined there is callable from root.html.heex:
defmodule MyAppWeb.Layouts do
use MyAppWeb, :html
embed_templates "layouts/*"
def onyxmetric_site_id, do: Application.get_env(:my_app, :onyxmetric, [])[:site_id]
endEdit the root layout
Add the tag inside <head>, after the app.css and app.js tags:
<script
:if={onyxmetric_site_id()}
src={"https://app.onyxmetric.com/api/script.js?siteId=#{onyxmetric_site_id()}"}
async
></script>With the variable unset, the tag is skipped, so dev and test stay untracked.
LiveView navigation (<.link navigate>, <.link patch>, push_navigate/2, push_patch/2) uses the History API and keeps the root layout, so the script stays loaded and each navigation is recorded as a pageview.
Check that it works
Load your live site and click through a few pages. Pageviews show up in the OnyxMetric dashboard within seconds.
If nothing arrives:
- View the page source and search for
script.js?siteId=to confirm the tag is present. - In the browser's Network tab, check that
script.jsreturns200and that requests go to/api/track. - Turn off ad blockers, or proxy the script through your own domain.
- Read script troubleshooting for other causes.
Troubleshooting
- Tag missing:
runtime.exsis evaluated at boot, so restart the app or release after changing the variable. CheckApplication.get_env(:my_app, :onyxmetric)iniex -S mix. - CSP plug: allow
app.onyxmetric.cominscript-srcandconnect-src, or proxy the script.
Next steps
- Track custom events such as signups, purchases, and clicks.
- Identify users to tie sessions to accounts.
- Proxy the script through your own domain to get past ad blockers.
- Script attributes let you skip or mask URLs and tag events.