Write instrumentation-client.ts so the shop's analytics count client-side navigations as page views
Leaf and Kettle's analytics counted a page view on every page load. Since the shop moved to the App Router, a visit that opens five teas shows one view. Write instrumentation-client.ts, the file Next.js runs in the browser once the HTML has loaded and before React hydrates, so that every page a visitor sees counts once, through sendPageView(path) from lib/analytics.ts.
Count the page the visitor lands on when the file loads, by location.pathname.
Export onRouterTransitionStart(url, navigationType). Next.js's router calls it at the start of every client-side navigation: a <Link> click, router.push, or router.replace (type "push" or "replace"), and Back or Forward (type "traverse"). For a push or replace, url is the address as the link or the call wrote it, usually relative, like /teas/mint?ref=mail. For Back and Forward it's the full address, like http://localhost:3000/teas/green.
Send the path only, without the query string or the hash: the shop's search puts what customers type into the query. And don't count a navigation that stays on the path counted last, like changing the filters on /teas from /teas?type=green to /teas?type=black, or following a link to /teas#gift-boxes while on /teas.
instrumentation-client.tsimport { sendPageView } from "@/lib/analytics";
// Counts the page the visitor lands on.
sendPageView(location.pathname);
lib/analytics.ts (read-only)// The shop's analytics client. Each page view waits here until the next batch is sent.
export const queued: string[] = [];
export function sendPageView(path: string) {
queued.push(path);
}
- counts the page the visitor lands on, once, when the file loads
- counts a Link click by its path, without the query or the hash
- counts Back and Forward, which pass the full address
- doesn't count a navigation that stays on the same path
- counts a page again after the visitor has been somewhere else
- doesn't count the landing page twice when the first navigation stays on it
The answer
Write it yourself first. Then compare it with a reference solution and the checks it passes.
Checking your sign-in…