← All IntegrationsIntegration

Analytics for Next.js

Next.js powers some of the fastest sites on the web. BetterMeter adds privacy-first analytics without slowing them down — one script tag in your root layout, automatic route change tracking, and zero cookies. Works with both App Router and Pages Router.

Add the tracker to your root layout

With the App Router, add the BetterMeter script to your root layout.tsx. The deferattribute ensures it never blocks rendering. The tracker runs entirely client-side — it's ignored during Server Component rendering.

app/layout.tsx
import Script from "next/script";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        <Script
          defer
          data-site="your-domain.com"
          src="https://bettermeter.com/api/script"
          strategy="afterInteractive"
        />
      </body>
    </html>
  );
}

Proxy through Next.js rewrites

Ad blockers sometimes block third-party analytics scripts. You can proxy BetterMeter through your own domain using Next.js rewrites — the script loads from your origin, so blockers never see it.

next.config.ts
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  async rewrites() {
    return [
      {
        source: "/bm/script",
        destination: "https://bettermeter.com/api/script",
      },
      {
        source: "/bm/event",
        destination: "https://bettermeter.com/api/event",
      },
    ];
  },
};

export default nextConfig;

App Router vs Pages Router

  • 01 App Router — Add the script in app/layout.tsx as shown above. Route changes via next/navigation are tracked automatically.
  • 02 Pages Router — Add the script in pages/_app.tsx or pages/_document.tsx. Client-side navigations via next/router are detected via the History API.
  • 03 Server Components — The tracker script only runs in the browser. It has zero impact on Server Component rendering or streaming.
  • 04 Static export — Works with output: "export" too. The script tag is included in the static HTML.
< 1 KB
Script size
No Cookies
GDPR-compliant
SPA Tracking
History API detection
AI Detection
ChatGPT, Claude, etc.
Bot Filtering
Separate bot traffic
Proxy Support
Via next.config rewrites