OnyxMetric
Integration Guides

VitePress

Add OnyxMetric analytics to your VitePress docs

VitePress has a head option in .vitepress/config.ts that adds tags to every page. A custom theme is the alternative when you need to load the script conditionally at runtime.

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 VitePress

Edit .vitepress/config.ts (or .js / .mts) and add the tag to head:

.vitepress/config.ts
export default defineConfig({
  head: [
    [
      "script",
      {
        src: "https://app.onyxmetric.com/api/script.js?siteId=YOUR_SITE_ID",
        async: "",
      },
    ],
  ],
});

The empty string for async is deliberate. VitePress renders it as a boolean attribute.

To track production only, make head conditional:

.vitepress/config.ts
const isProd = process.env.NODE_ENV === "production";

export default defineConfig({
  head: isProd
    ? [["script", { src: "https://app.onyxmetric.com/api/script.js?siteId=YOUR_SITE_ID", async: "" }]]
    : [],
});

For runtime control, inject the tag from a custom theme in .vitepress/theme/index.ts:

.vitepress/theme/index.ts
export default {
  extends: DefaultTheme,
  enhanceApp() {
    if (typeof window === "undefined") return;

    const el = document.createElement("script");
    el.src = "https://app.onyxmetric.com/api/script.js?siteId=YOUR_SITE_ID";
    el.async = true;
    document.head.appendChild(el);
  },
} satisfies Theme;

The window check keeps the injector out of the server-side build.

VitePress navigates client-side through the History API, which OnyxMetric records as pageviews.

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 in vitepress dev: with the isProd guard it renders only in vitepress build. Remove the guard to test locally.
  • Pageviews stop after navigation: look in the browser console for errors from other head scripts or theme code. An exception during a route change can block the listener.

Next steps

On this page