
28 November 2026 · 2 min read
Thirteen Unit Tests Passed and Production Disagreed
Pageview tracking on this site was counting things nobody looked at. Every <Link> that scrolls into view is prefetched, and a page view can trigger ten to twenty-five of those, so the numbers were mostly the site talking to itself. The fix looked simple: ignore requests that carry the prefetch headers.
The change that passed#
I filtered on the RSC headers Next.js sends for prefetches, Next-Router-Prefetch and its relatives, plus the ?_rsc query parameter. Thirteen unit tests covered it and all passed.
Then I made five test requests against production. Four were still recorded. So the filter was doing nothing in the place that mattered.
Why the tests could not see it#
The tests imported the middleware function and called it directly with hand-built requests that included the headers. In a real server, the request goes through Next.js's middleware adapter first, and that adapter deletes those flight headers and strips ?_rsc before your code runs. My function never saw the headers it was written to look for. My tests supplied a world in which the headers survived, and in production they did not.
The fix#
There is a Next.js config option that stops the adapter normalising the URL, skipProxyUrlNormalize in Next 16 (the older name is skipMiddlewareUrlNormalize). With it set, the headers and the query parameter reach the proxy intact. I checked it against a local next build && next start first, then against production, where one of five test requests was recorded instead of four, which is the expected count.
What I changed about how I test#
- Anything that depends on request headers or URLs inside middleware has to be verified against a real
next start, not only through a direct function call. A unit test of a function that sits behind a framework layer proves the function, not the behaviour. - When a feature is observable from outside, make one real request and count the effect. Five requests and a count took two minutes and caught what thirteen tests did not.
I also learned that GitHub did not auto-close the issue from the merged pull request's "Closes" line, because the merge came from a CI job, so now I close those by hand after verifying.