Next.js Analytics: Web Vitals, Events, and Consent
Analytics in a Next.js app has three audiences pulling in different directions. Product teams want every click recorded. Performance engineers want real-user Core Web Vitals without a third-party script tanking the Lighthouse score. Legal wants consent before any cross-border cookie is set. Satisfying all three is a design problem before it is a code problem: decide what you must measure, what you may measure, and which tool measures each â then wire the smallest possible set of scripts.
This lesson assembles a modern analytics stack: framework-native Web Vitals collection, a first-party event layer that survives navigation, consent-gated loading of third-party tags, an ingestion endpoint that keeps the data clean, and client error tracking so failures reach you before users tweet about them.
There is also an ordering decision hidden in the stack: what runs on the server and what runs in the browser. Vitals collection and error reporting must observe the client because that is where the experience happens. Event capture lives in the client but posts to your own server, where consent checks, validation, and scrubbing can be enforced in a place the browser cannot skip. Third-party tags sit behind the consent gate and outside your critical path entirely. Keeping those three layers distinct is what lets you swap vendors later without rewriting the measurement plan â and the measurement plan is the part that actually deserves stability.
Prerequisites
- !Comfort editing the root layout
- !Understanding of client components and effects
- !Familiarity with environment variables
What You'll Learn
- 1Install and configure Vercel Analytics and Speed Insights
- 2Build a typed first-party event hook that batches and flushes reliably
- 3Load third-party tags only after consent
- 4Capture unhandled client errors with context
Web Vitals without the third-party tax
The fastest analytics script is the one that does not exist, and the second fastest is the one built for the framework. Vercel's analytics packages collect Core Web Vitals from real sessions with a tiny script that does not block rendering and does not set cookies by default â which keeps you outside consent requirements in most jurisdictions while still giving performance data.
// app/layout.js
import { Analytics } from '@vercel/analytics/react';
import { SpeedInsights } from '@vercel/speed-insights/next';
export const metadata = {
title: 'Acme Dashboard',
};
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
{children}
<Analytics />
<SpeedInsights />
</body>
</html>
);
}
Both components render invisible no-op elements until the client hydrates; neither participates in layout. Check the reported p75 values weekly â a regression in INP after a feature launch is the signal that a new client component monopolized the main thread.
A first-party event layer
Product events â signup started, plan upgraded, export downloaded â usually go to a warehouse you control before they go anywhere else. A small hook that batches events and POSTs them to your own endpoint keeps the data first-party, avoids ad-blocker losses on known vendor domains, and gives you a single place to add consent checks.
// lib/analytics.js
'use client';
import { useCallback, useEffect, useRef } from 'react';
export function useAnalytics() {
const queueRef = useRef([]);
const timerRef = useRef(null);
const flush = useCallback(async () => {
if (queueRef.current.length === 0) return;
const batch = queueRef.current.splice(0, queueRef.current.length);
try {
await fetch('/api/events', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ events: batch }),
keepalive: true,
});
} catch {
// Dropping a batch of analytics beats blocking navigation
}
}, []);
const track = useCallback(
(name, properties = {}) => {
queueRef.current.push({
name,
properties,
path: window.location.pathname,
ts: Date.now(),
});
if (timerRef.current === null) {
timerRef.current = setTimeout(() => {
timerRef.current = null;
flush();
}, 3000);
}
},
[flush]
);
useEffect(() => {
const onHide = () => flush();
window.addEventListener('pagehide', onHide);
document.addEventListener('visibilitychange', onHide);
return () => {
window.removeEventListener('pagehide', onHide);
document.removeEventListener('visibilitychange', onHide);
if (timerRef.current !== null) clearTimeout(timerRef.current);
flush();
};
}, [flush]);
return { track };
}
keepalive lets the fetch survive navigation, and the visibility handlers flush the final batch when the tab goes to the background â the moment most naive implementations lose their last events.
// components/UpgradeButton.js
'use client';
import { useAnalytics } from '@/lib/analytics';
export function UpgradeButton({ planId }) {
const { track } = useAnalytics();
return (
<button
type="button"
onClick={() => {
track('upgrade_clicked', { planId, source: 'pricing_table' });
window.location.href = `/checkout?plan=${planId}`;
}}
>
Upgrade
</button>
);
}
Name events by the action, not by the element: upgrade_clicked with a source property survives button redesigns; button_blue_3_click does not.
Consent-gated third-party scripts
Marketing platforms still want their pixels. The pattern that satisfies both legal and performance is a consent store consulted before any third-party script mounts, with the scripts themselves loaded dynamically so they never appear in the critical path.
// components/ConsentScript.js
'use client';
import { useEffect, useState } from 'react';
export function ConsentScript({ vendor, src, consentKey }) {
const [allowed, setAllowed] = useState(false);
useEffect(() => {
const consent = localStorage.getItem('cookie-consent');
const onConsent = (e) => setAllowed(e.detail[consentKey] === true);
window.addEventListener('consent-updated', onConsent);
if (consent) {
try {
const parsed = JSON.parse(consent);
setAllowed(parsed[consentKey] === true);
} catch {
setAllowed(false);
}
}
return () => window.removeEventListener('consent-updated', onConsent);
}, [consentKey]);
useEffect(() => {
if (!allowed) return;
const script = document.createElement('script');
script.src = src;
script.async = true;
script.dataset.vendor = vendor;
document.head.appendChild(script);
return () => {
script.remove();
};
}, [allowed, src, vendor]);
return null;
}
Mount one ConsentScript per vendor in the root layout. When the user changes preferences, dispatch consent-updated on the window and the components load or unload themselves. Unloading is imperfect for some vendors â cookies may persist â so the honest implementation asks for consent before the first set rather than promising full revocation.
Error tracking with enough context
Client-side exceptions are invisible in server logs. A global error boundary paired with a report handler captures the stack, the route, and a release identifier so you can correlate spikes with deploys.
// components/ErrorReporter.js
'use client';
import { useEffect } from 'react';
export function ErrorReporter() {
useEffect(() => {
const onError = (event) => {
fetch('/api/client-errors', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
message: event.message,
source: event.filename,
line: event.lineno,
stack: event.error?.stack?.slice(0, 2000),
route: window.location.pathname,
release: process.env.NEXT_PUBLIC_RELEASE_SHA,
}),
keepalive: true,
}).catch(() => {});
};
const onRejection = (event) => {
onError({
message: String(event.reason?.message ?? event.reason),
filename: '',
lineno: 0,
error: event.reason instanceof Error ? event.reason : undefined,
});
};
window.addEventListener('error', onError);
window.addEventListener('unhandledrejection', onRejection);
return () => {
window.removeEventListener('error', onError);
window.removeEventListener('unhandledrejection', onRejection);
};
}, []);
return null;
}
Scrub the payload server-side before storing it: stack traces can contain query strings with tokens, and your error endpoint is as much of an attack surface as any other route. The same handler should attach the release identifier, route path, and browser context so a spike after a deploy can be correlated with the change that shipped moments earlier, and so triage begins with the right hypothesis instead of guesswork.
An ingestion endpoint that keeps the data clean
Your own event endpoint is only useful if it is defended and disciplined. Three checks belong in the handler before anything touches storage. Validate the shape: an event array capped at a sane batch size, each entry with a name from an allowlist and a properties object under a size limit, rejects both malformed clients and someone attempting to use your endpoint as free storage. Scrub for known secrets with a pattern pass over string values â tokens, emails when the schema does not call for them, anything matching your internal key formats. And rate-limit by session or IP so a runaway loop in your own client cannot write a hundred thousand duplicates before anyone notices.
Once events are accepted, enforce the taxonomy at write time rather than downstream. A name that does not appear in the registry gets rejected with a 400 during development and logged for review in production; this catches the well-meaning pull request that ships a duplicate variant like checkout_started versus checkout-started. Deduplicate near-identical retries with a client-generated event ID so a retried batch after a timeout does not inflate counts.
Storage itself is a simpler decision than it looks. Append-only rows in a relational table are entirely adequate until volume makes them painful; a columnar or event-log store earns its complexity when analysts start querying months of history interactively. Either way, keep the raw layer immutable â corrected or enriched copies live in downstream tables, because the ability to reprocess raw events after you discover a logging bug is the difference between fixing history and guessing at it.
A minimal event taxonomy
Teams drown in unbounded event names within months. A short governance rule prevents it: every event must have a named owner, a documented purpose, and a review when added. A table in the handbook beats any amount of downstream cleanup.
| Event | Properties | Owner | Purpose |
|---|---|---|---|
| signup_started | source | Growth | Funnel top |
| signup_completed | plan | Growth | Conversion |
| upgrade_clicked | planId, source | Revenue | Monetization |
| export_downloaded | format, rows | Product | Feature value |
| error_boundary_hit | route, release | Platform | Reliability |
Quarterly, delete events nobody queries. An unexamined event stream is storage cost and compliance risk wearing a product disguise.
Common Mistakes
Loading Google Analytics in the head unconditionally
Fix: Gate third-party scripts behind consent and inject them dynamically so they never block first paint.
Naming events after DOM elements
Fix: Name them after user intent with stable property keys so redesigns do not break historical data.
Dropping the final event batch on navigation
Fix: Use keepalive fetches and pagehide or visibilitychange flushes to capture the last moments of a session.
Logging raw error payloads with query strings intact
Fix: Scrub tokens and PII on the ingestion endpoint before persisting anything.
Best Practices
- Prefer first-party, cookieless vitals collection for performance measurement
- Route product events through one hook so consent and batching live in one place
- Version releases and attach the identifier to every error report
- Audit the event taxonomy quarterly and delete what nobody uses
Interview Questions
Q1: Why collect Web Vitals first-party instead of through a tag manager?
Framework-native scripts are smaller, cookieless by default, and unaffected by ad blockers â so the data is both faster for users and more complete.
Q2: Where should consent checks live in a Next.js app?
In the client hook or component that would mount the third-party script, with a custom event that reacts to preference changes.
Q3: How do you avoid losing analytics events on navigation?
Send with keepalive: true and flush on pagehide and visibilitychange so the final batch survives the page teardown.
Key Takeaways
- Framework-native analytics give Core Web Vitals without consent or performance cost.
- A first-party event hook with batching keeps data ownership and reliability in your hands.
- Consent gates belong before any third-party script mounts, not after.
- Error tracking with release context turns silent client failures into actionable reports.
- A small governed event taxonomy beats an unbounded firehose every time.