Add Privatus Analytics to Next.js
Add cookieless analytics to Next.js with next/script, for the App or Pages Router, with custom events from client components.
Add the script#
App Router: use next/script in the root layout, app/layout.tsx:
tsx
import Script from 'next/script'
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
{children}
<Script defer src="https://privatusstats.com/js/pa.js" data-site="pa_YOURSITEID" data-modules="engage,auto,vitals,clicks,ask" strategy="afterInteractive" />
</body>
</html>
)
}
Pages Router: render the same <Script> in pages/_app.tsx.
Next.js client navigations use history.pushState, which the tracker
follows with its default data-spa="auto". Every tracker option is a
data- attribute on the script (see attributes).
Track events#
tsx
'use client'
export function UpgradeButton() {
return (
<button onClick={() => window.privatus?.track('Upgrade', { plan: 'pro' })}>
Upgrade
</button>
)
}
For types on window.privatus, add the declarations from the
JavaScript API page.