Skip to content

Install Statsdot on Next.js

Updated October 13, 2026

App Router

Add the script to your root layout, app/layout.tsx:

import Script from 'next/script'

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        <Script
          src="https://statsdot.com/js/script.js"
          data-domain="yoursite.com"
          strategy="afterInteractive"
        />
      </body>
    </html>
  )
}

Pages Router

Add a plain script tag to pages/_document.tsx:

import { Html, Head, Main, NextScript } from 'next/document'

export default function Document() {
  return (
    <Html>
      <Head>
        <script defer data-domain="yoursite.com" src="https://statsdot.com/js/script.js" />
      </Head>
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  )
}

Route changes

Next.js changes pages with the browser's history API, and Statsdot listens to it, so every route change counts as a pageview. No router events to wire up.

Custom events

<button onClick={() => window.statsdot?.track('Signup')}>Create account</button>

In TypeScript, declare the global once:

declare global {
  interface Window { statsdot?: { track: (name: string, label?: string) => void } }
}

Development

Visits from localhost are ignored, so your local development does not add to your numbers.