OnyxMetric
Integration Guides

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/runtime.exs
config :my_app, :onyxmetric, site_id: System.get_env("ONYXMETRIC_SITE_ID")
export ONYXMETRIC_SITE_ID=YOUR_SITE_ID

Expose it to the layout

Templates in components/layouts/ are embedded in MyAppWeb.Layouts, so a function defined there is callable from root.html.heex:

lib/my_app_web/components/layouts.ex
defmodule MyAppWeb.Layouts do
  use MyAppWeb, :html

  embed_templates "layouts/*"

  def onyxmetric_site_id, do: Application.get_env(:my_app, :onyxmetric, [])[:site_id]
end

Edit the root layout

Add the tag inside <head>, after the app.css and app.js tags:

lib/my_app_web/components/layouts/root.html.heex
<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.js returns 200 and 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.exs is evaluated at boot, so restart the app or release after changing the variable. Check Application.get_env(:my_app, :onyxmetric) in iex -S mix.
  • CSP plug: allow app.onyxmetric.com in script-src and connect-src, or proxy the script.

Next steps

On this page