Next.js integration
Track Next.js apps with @puremetrix/tracker: load the cookieless script via the React provider, send pageviews and custom events, and optionally route data through your own domain (Vercel rewrite recipe included).
Prerequisites
- Next.js 13+ (App Router or Pages Router).
- A PureMetrix site and public key from app.puremetrix.org.
Install
npm install @puremetrix/tracker App Router
Wrap the root layout with PureMetrixProvider from @puremetrix/tracker/react. Defaults assume a same-origin proxy (/px/js, /px/event). Point scriptSrc / api at collect.puremetrix.org if you do not use the proxy.
// app/layout.tsx
import { PureMetrixProvider } from '@puremetrix/tracker/react';
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<PureMetrixProvider
domain="example.com"
key="YOUR_PUBLIC_KEY"
// optional without proxy:
// scriptSrc="https://collect.puremetrix.org/js/script.js"
// api="https://collect.puremetrix.org/api/event"
>
{children}
</PureMetrixProvider>
</body>
</html>
);
} Page changes without a reload
The provider loads the tracker script. In the App Router, moving to another page does not reload the document, so send a pageview whenever the route changes:
'use client';
import { useEffect } from 'react';
import { usePathname, useSearchParams } from 'next/navigation';
import { usePureMetrix } from '@puremetrix/tracker/react';
export function PureMetrixPageviews() {
const pathname = usePathname();
const searchParams = useSearchParams();
const { track } = usePureMetrix();
useEffect(() => {
track('pageview');
}, [pathname, searchParams, track]);
return null;
} Mount <PureMetrixPageviews /> inside the provider (for example in the root layout body).
Custom events
const { track } = usePureMetrix();
track('SignupClick', { props: { plan: 'growth' } }); Or from non-React code: import { init, track } from '@puremetrix/tracker'.
Vercel proxy (recommended)
Add rewrites so browsers load the script and send events via your own domain (ad blockers then block them less often). See Vercel proxy and adapters/proxy/vercel.json. After proxying, keep provider defaults (scriptSrc="/px/js", api="/px/event") or set scriptFile="script.js" if you serve the file under /px/js/script.js.
Verify
- In a private window, both the first page load and later page changes send events.
- The Network tab shows requests to
/px/…(or collect.puremetrix.org) with your public key. - Dashboard numbers update within about a minute.