Next.js IntegrationReact / App Router & Pages Router

Sub-2 KB analytics for Next.js App Router without router hooks.

Drop one next/script tag into app/layout.tsx to track App Router transitions, outbound clicks, downloads, and custom events with zero cookies and zero CLS or INP regression.

Imtiaz Rayhan
Imtiaz RayhanCo-Founder & Lead Engineer, DotCamp & TrimStats
Tested against Next.js & live TrimStats APIs
Seeded demo workspace
TrimStats Overview dashboard measuring Next.js routes in strict cookie-less mode with 42 live visitors and 2m 28s active visit timeTrimStats Overview dashboard measuring Next.js routes in strict cookie-less mode with 42 live visitors and 2m 28s active visit time
Every App Router soft navigation appears automatically under Top Pages alongside visibility-aware active dwell time and click-to-filter segments.
Direct answer

How do you add privacy-first analytics to Next.js App Router without hurting Core Web Vitals?

Add TrimStats to Next.js by placing a single next/script tag (strategy="afterInteractive") in app/layout.tsx pointing to https://collect.trimstats.com/t.js. The 1.96 KB gzipped script automatically intercepts history.pushState and popstate transitions across App Router and Pages Router with zero usePathname hooks, zero cookies, and strict Content-Security-Policy compatibility.

Step-by-step setup for Next.js

Copy-paste implementation verified against the live TrimStats tracker and collector APIs.

  1. 1

    Add the TrimStats script in app/layout.tsx

    Render next/script with strategy="afterInteractive" inside your root layout. Store your pk_live_... site key in NEXT_PUBLIC_TRIMSTATS_SITE_KEY so preview and production environments stay separated.

    app/layout.tsxtsx
    1import Script from 'next/script';
    2import type { ReactNode } from 'react';
    3
    4export default function RootLayout({ children }: { children: ReactNode }) {
    5 const siteKey = process.env.NEXT_PUBLIC_TRIMSTATS_SITE_KEY;
    6
    7 return (
    8 <html lang="en">
    9 <body>
    10 {children}
    11 {siteKey && (
    12 <Script
    13 src="https://collect.trimstats.com/t.js"
    14 data-site={siteKey}
    15 strategy="afterInteractive"
    16 />
    17 )}
    18 </body>
    19 </html>
    20 );
    21}
    Works identically in Next.js App Router (Server Components) and Pages Router.
  2. 2

    Add ambient TypeScript types for window.trimstats

    Declare window.trimstats once so every Client Component gets full autocomplete for custom events, identify(), and attribution snapshots while using optional chaining safely.

    src/types/trimstats.d.tsts
    1export interface TrimStatsAttribution {
    2 vid: string;
    3 uid: string;
    4 ref: string;
    5 lp: string;
    6 utm_source: string;
    7 utm_medium: string;
    8 utm_campaign: string;
    9}
    10
    11export interface TrimStatsFn {
    12 (cmd: 'event', name: string, props?: Record<string, string | number | boolean | null>): void;
    13 (cmd: 'identify', userId: string): void;
    14 q?: Array<unknown[]>;
    15 attribution?: () => TrimStatsAttribution;
    16}
    17
    18declare global {
    19 interface Window {
    20 trimstats?: TrimStatsFn;
    21 }
    22}
  3. 3

    Allow collect.trimstats.com in your Next.js CSP headers

    TrimStats uses zero eval() and zero inline script execution. If your next.config.ts sets a strict Content-Security-Policy, add the collector origin to script-src and connect-src.

    next.config.ts (CSP directives)http
    Content-Security-Policy:
    script-src 'self' https://collect.trimstats.com;
    connect-src 'self' https://collect.trimstats.com;
  4. 4

    Verify live beacons across client-side <Link> navigations

    Open DevTools Network tab with Preserve log enabled, navigate between two Next.js routes, and confirm t.js loads with HTTP 200 and POST /v1/collect returns 202 Accepted on each route change.

Recommended taxonomy

High-signal custom events to track for Next.js

Fire any event with window.trimstats?.('event', name, props) and attach it to conversion goals or multi-step ClickHouse funnels.

Event nameWhen to fireSample properties
signup_completedUser finishes account creation inside your Next.js signup Server Action or API callback.{"method":"email","plan":"free"}
pricing_plan_selectedVisitor clicks a tier CTA button on /pricing.{"plan":"growth","billing":"monthly"}
docs_snippet_copiedDeveloper copies an installation or SDK snippet from documentation pages.{"framework":"nextjs"}
checkout_startedAuthenticated user initiates a Stripe, Paddle, or Polar checkout session.{"provider":"stripe","tier":"growth"}
cta_clickedVisitor clicks a primary hero or bottom conversion CTA on marketing pages.{"location":"hero","page":"/features/revenue-attribution"}

TrimStats t.js transfer weight keeps Next.js Core Web Vitals green

Measured bytes from packages/tracker/dist/t.js vs enforced 3 KiB CI ceiling

KB
Brotli transfer(1,732 B)
1.73 KB
Gzip transfer(1,964 B)
1.96 KB
CI gzip ceiling(3,072 B)
3.07 KB
Raw minified JS(3,508 B)
3.51 KB

Because t.js loads deferred at 1.96 KB gzipped and sends beacons via text/plain sendBeacon, Next.js hydration and LCP stay unaffected.

Methodology: Measured directly from compiled packages/tracker/dist/t.js with gzip level 9 and brotli compression.

Source: TrimStats repository build artifact (packages/tracker/dist/t.js)
View chart data table
LabelPayload size
Brotli transfer1.73 KB
Gzip transfer1.96 KB
CI gzip ceiling3.07 KB
Raw minified JS3.51 KB

Next.js analytics FAQ

Implementation details, privacy trade-offs, and event-quota answers.

Do I need a usePathname or useEffect hook for Next.js App Router pageviews?
No. TrimStats automatically wraps history.pushState and listens for browser popstate events inside t.js, so every client-side <Link> transition and back/forward navigation in Next.js App Router and Pages Router is recorded automatically without writing a React client wrapper.
Does TrimStats work inside Next.js React Server Components?
Yes. Your root app/layout.tsx stays a pure Server Component because next/script renders cleanly from Server Components. You only invoke window.trimstats?.("event", ...) inside Client Components or interactive event handlers.
How do I prevent Vercel preview deployments or localhost from polluting production data?
Guard the <Script> tag behind NEXT_PUBLIC_TRIMSTATS_SITE_KEY set only for your Production environment in Vercel, or set localStorage.setItem("trimstats_ignore", "1") in your own browser DevTools to suppress local hits.
Does TrimStats require unsafe-inline or unsafe-eval in Next.js CSP headers?
No. TrimStats never uses eval() or inline JavaScript execution when loaded via next/script or <script defer>. Adding https://collect.trimstats.com to script-src and connect-src is sufficient for strict CSP policies.
Can I track Stripe revenue attribution from a Next.js checkout route?
Yes. Read window.trimstats?.attribution?.() on the client before posting to your Next.js /api/checkout Route Handler, attach the snapshot to Stripe metadata.trimstats, and register your TrimStats Stripe webhook endpoint.
Does TrimStats require a cookie consent banner on Next.js marketing sites?
No in default cookie-less mode. TrimStats writes zero cookies and zero localStorage, hashes visitors transiently on German EU servers with a 24-hour rotating salt, and adds only 1.96 KB gzipped to your Next.js layout.
Imtiaz Rayhan
Integration guide verified by
Imtiaz Rayhan (Co-Founder & Lead Engineer, DotCamp & TrimStats)

Co-founder of DotCamp LLC in Brooklyn, NY and lead engineer of TrimStats. Ships privacy-first web analytics, ClickHouse pipelines, and WordPress plugins used on 115,000+ active sites.

  • • Architect of the TrimStats 1.96 KB gzipped browser tracker, Fastify collector, and ClickHouse MergeTree pipeline
  • • Co-founder of DotCamp LLC (est. 2019), creator of Ultimate Blocks (50,000+ installs), WP Table Builder (50,000+ installs), Tableberg, and OptimizeCamp
  • • WordPress.org plugin & theme developer since 2016 with 1,200+ community support replies and 5M+ cumulative plugin downloads

Verification standard: Code snippets, custom event payloads, and webhook contracts for Next.js are verified against the live TrimStats tracker (1.96 KB gzipped) and collector schema as of 2026-11-30.

Instrument Next.js in under 60 seconds

Start on Starter ($17/month for 100,000 monthly events), with cookie-less privacy defaults and full access to revenue webhooks, funnels, cohorts, and UI friction.

Verified against live TrimStats APIs and tracker bundle.