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