OnyxMetric
Integration Guides

Astro

Add OnyxMetric analytics to your Astro site

Astro pages normally share one layout component that renders the <html> document. Add the tag to that layout's <head> and every page using it is tracked.

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 Astro

Open your shared layout, usually src/layouts/Layout.astro, and add the tag inside <head>. The is:inline directive stops Astro from bundling or rewriting it:

src/layouts/Layout.astro
---
const { title } = Astro.props;
---
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>{title}</title>
    <script is:inline src="https://app.onyxmetric.com/api/script.js?siteId=YOUR_SITE_ID" async></script>
  </head>
  <body>
    <slot />
  </body>
</html>

Without a shared layout, add the same tag to each file in src/pages/; a layout is simpler to maintain.

A default Astro site is multi-page, so every navigation is a full load and a pageview. With view transitions on, client-side navigation is tracked when the URL changes.

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.

Track custom events

Call window.onyx.event() from a client-side <script> in any .astro component, or from a framework island the way that framework would.

src/components/TrackedButton.astro
<button id="tracked-button">Click me</button>

<script>
  document.getElementById("tracked-button")?.addEventListener("click", () => {
    window.onyx?.event("astro_button_click", { source: "TrackedButton.astro" });
  });
</script>

Troubleshooting

  • Pageviews missing with view transitions: uncommon. If it happens, listen for astro:after-swap in a client script and call window.onyx.pageview().
  • Serving the script from your own domain: see the Astro proxy guide.

Next steps

On this page