Next.js
Add OnyxMetric analytics to your Next.js app
Next.js has a Script component that decides when a third-party script loads. Render it once in the root layout (App Router) or in _app (Pages Router).
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 Next.js
Use next/script with strategy="afterInteractive" rather than a raw <script> tag. The strategy handles load timing, so the async attribute is unnecessary.
import Script from "next/script";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
{children}
<Script src="https://app.onyxmetric.com/api/script.js?siteId=YOUR_SITE_ID" strategy="afterInteractive" />
</body>
</html>
);
}import Script from "next/script";
export default function MyApp({ Component, pageProps }) {
return (
<>
<Component {...pageProps} />
<Script src="https://app.onyxmetric.com/api/script.js?siteId=YOUR_SITE_ID" strategy="afterInteractive" />
</>
);
}Navigation through <Link> and router.push() is recorded as pageviews with no extra code.
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.
Track custom events
Use window.onyx.event() in a client component. The script loads after hydration and components may also render on the server, so check before calling.
"use client";
export default function MyButton({ title }) {
const handleClick = () => {
if (typeof window !== "undefined") {
window.onyx?.event("button_click", { buttonTitle: title });
}
};
return <button onClick={handleClick}>{title}</button>;
}Troubleshooting
- Serving the script from your own domain: Next.js rewrites can forward the script and its API. See the Next.js proxy guide.
- Missing pageviews after client navigation: uncommon. Only if the default fails, call
window.onyx.pageview()after the route change.
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.