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.


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
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.tsxtsx1import Script from 'next/script';2import type { ReactNode } from 'react';34export default function RootLayout({ children }: { children: ReactNode }) {5 const siteKey = process.env.NEXT_PUBLIC_TRIMSTATS_SITE_KEY;67 return (8 <html lang="en">9 <body>10 {children}11 {siteKey && (12 <Script13 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
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.tsts1export 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}1011export 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}1718declare global {19 interface Window {20 trimstats?: TrimStatsFn;21 }22} - 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)httpContent-Security-Policy:script-src 'self' https://collect.trimstats.com;connect-src 'self' https://collect.trimstats.com; - 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.
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 name | When to fire | Sample properties |
|---|---|---|
| signup_completed | User finishes account creation inside your Next.js signup Server Action or API callback. | {"method":"email","plan":"free"} |
| pricing_plan_selected | Visitor clicks a tier CTA button on /pricing. | {"plan":"growth","billing":"monthly"} |
| docs_snippet_copied | Developer copies an installation or SDK snippet from documentation pages. | {"framework":"nextjs"} |
| checkout_started | Authenticated user initiates a Stripe, Paddle, or Polar checkout session. | {"provider":"stripe","tier":"growth"} |
| cta_clicked | Visitor 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
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.
View chart data table
| Label | Payload size |
|---|---|
| Brotli transfer | 1.73 KB |
| Gzip transfer | 1.96 KB |
| CI gzip ceiling | 3.07 KB |
| Raw minified JS | 3.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?
Does TrimStats work inside Next.js React Server Components?
How do I prevent Vercel preview deployments or localhost from polluting production data?
Does TrimStats require unsafe-inline or unsafe-eval in Next.js CSP headers?
Can I track Stripe revenue attribution from a Next.js checkout route?
Does TrimStats require a cookie consent banner on Next.js marketing sites?
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.
Related documentation and guides
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.