Next.js
Next.js integration guide
For Next.js applications, you can add PureStats tracking using the built-in Script component or the document file.
Option 1: Using next/script (Recommended)
For Next.js 11+, use the Script component in your _app.js or _app.tsx:
// pages/_app.js or pages/_app.tsx
import Script from 'next/script'
export default function MyApp({ Component, pageProps }) {
return (
<>
<Script
defer
data-domain="yourdomain.com"
src="https://purestats.io/pf.min.js"
strategy="afterInteractive"
/>
<Component {...pageProps} />
</>
)
}
Option 2: Using _document.js
Alternatively, add the script in your _document.js or _document.tsx:
// pages/_document.js
import { Html, Head, Main, NextScript } from 'next/document'
export default function Document() {
return (
<Html>
<Head>
<script
defer
data-domain="yourdomain.com"
src="https://purestats.io/pf.min.js"
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
App Router (Next.js 13+)
For Next.js 13+ with the App Router, add the script in your root layout:
// app/layout.tsx
import Script from 'next/script'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<head>
<Script
defer
data-domain="yourdomain.com"
src="https://purestats.io/pf.min.js"
strategy="afterInteractive"
/>
</head>
<body>{children}</body>
</html>
)
}
Tracking Custom Events
Track custom events in your Next.js components:
// components/SignupButton.tsx
export default function SignupButton() {
const handleClick = () => {
// Track the event
if (typeof window !== 'undefined' && window.purestats) {
window.purestats('Signup Click')
}
// Your signup logic here
}
return (
<button onClick={handleClick}>
Sign Up
</button>
)
}
TypeScript Support
Add type declarations for PureStats:
// types/global.d.ts
declare global {
interface Window {
purestats: (event: string, props?: { props?: Record<string, any> }) => void
}
}
export {}
Note: PureStats automatically tracks client-side navigation in Next.js. No additional configuration needed for route changes.