Write the function useReportWebVitals calls, so metrics reach your analytics in batches that survive the page closing
The root layout renders WebVitals, a Client Component that passes every metric to reportVital from lib/report-vitals.ts. Write reportVital(metric):
app/web-vitals.tsx"use client";
import { useReportWebVitals } from "next/web-vitals";
import { reportVital } from "@/lib/report-vitals";
export function WebVitals() {
useReportWebVitals(reportVital);
return null;
}
Don't send each metric on its own. Keep each one in a queue, with only the fields the dashboard reads: name, value, rating, id, navigationType, and page, the path of the metric's navigationURL without its query or hash (http://localhost:3000/teas/mint?ref=mail → /teas/mint).
Send everything in the queue as one JSON array to /api/vitals when the page is hidden (a visibilitychange event while document.visibilityState is "hidden"), and as soon as 10 metrics are waiting. Empty the queue when you send it, and never send an empty array.
Send with navigator.sendBeacon("/api/vitals", body). When the browser has no sendBeacon, or it returns false because it couldn't queue the data, send the same body with fetch instead: a POST with keepalive: true.
Add one visibilitychange listener, not one per metric, and don't touch document while the module loads: Next.js renders Client Components on the server too, so it loads this module there, where there's no document. Adding the listener when the first metric arrives does both.
lib/report-vitals.ts// The fields this file reads from each metric useReportWebVitals passes.
export type Metric = {
name: string;
value: number;
rating: string;
id: string;
navigationType: string;
navigationURL: string;
};
export function reportVital(metric: Metric) {
fetch("/api/vitals", { method: "POST", body: JSON.stringify(metric) });
}
- keeps the metrics until the page is hidden, then sends them in one beacon
- sends only the fields the dashboard reads, with the page's path and no query
- sends as soon as ten metrics are waiting, then starts a new batch
- uses fetch with keepalive when the browser refuses the beacon or has none
- sends nothing when the page becomes visible, or is hidden with nothing waiting
- adds one visibilitychange listener, however many metrics arrive
The answer
Write it yourself first. Then compare it with a reference solution and the checks it passes.
Checking your sign-in…