# A/B Testing on the Frontend: Three Bugs That Broke Our Test

8 min read

On one project, our A/B test said variant B won. It hadn’t. The test was broken, and all three bugs that broke it lived in frontend code: how we picked a variant, when we logged that a user was in the test, and how the page was cached.

This post goes through each bug, how it showed up, and how I handle it now in Next.js App Router. At the end there’s the checklist I run before launching a test and a live demo where you can break a test on purpose and watch the check catch it.

The red flag: the split wasn’t 50/50

You configure a test so half of the users see A and half see B. A hash spreads users between the groups, which is close enough to random. With 100,000 users you expect about 50,000 in each group. A small gap is normal, something like 50,200 and 49,800. Flip a fair coin 100,000 times and you won’t get exactly 50/50 either, but you also won’t get 53/47.

If you do get 53,000 and 47,000, that isn’t chance. Something in the code is losing or adding people in one group, and it’s doing it for a specific reason. Say variant B throws an error on old Android phones before it sends its event. Group B now holds mostly people on newer, faster phones, who tend to buy more anyway. B “wins”, even though B is broken and the two groups stopped being comparable.

This is called Sample Ratio Mismatch (SRM). A chi-square test answers the question “could a gap this big be random?”. If the answer is no, don’t trust the results, however good they look. Go find the bug first.

Bug 1: we logged assignment, not exposure

We sent the “user is in the experiment” event when the variant was assigned. The change itself was further down the page. Half the users counted in the test never scrolled to it, so they were measured without ever seeing the thing we were testing. That dilutes the effect. Worse, the share of people who never get there can differ between variants, and then the groups drift apart.

The fix is to log an exposure when the user actually sees the change, and to do it in every group, control included. I wrap the changed block in the same component in all variants and log once when half of it is on screen:

exposure.tsx
const observer = new IntersectionObserver(
([entry]) => {
if (!entry?.isIntersecting) return;
// threshold 0.5 alone never fires for a block taller than two screens
const seen =
entry.intersectionRatio >= 0.5 ||
entry.intersectionRect.height >= window.innerHeight / 2;
if (seen) {
logExposureOnce(experiment, variant, isOverride);
observer.disconnect();
}
},
{ threshold: Array.from({ length: 21 }, (_, i) => i / 20) },
);

The check for tall blocks matters. If one variant is a tall block, threshold: 0.5 can’t fire on a normal screen, so the tall variant logs fewer exposures than the short one, and you’re back to a broken split.

The event goes out with navigator.sendBeacon to a first-party endpoint (/api/e). Ad blockers don’t cut a first-party request, so whatever data you lose, you lose it the same way in every group. The endpoint takes the user ID from an httpOnly cookie, never from the request body.

Bug 2: bucketing with Math.random()

The variant was picked with Math.random(). Same user, next page load, different variant. One person ends up in both groups, and the group counts stop making sense.

The variant has to be a pure function of the user and the experiment. I hash the experiment key together with the user ID and take the result modulo 100:

assign.ts
export function assign<K extends ExperimentKey>(key: K, unitId: string) {
const { variants, weights, rollout } = experiments[key];
const control = variants[0] as VariantOf<K>;
// Hash 1: is this user in the experiment at all?
if (hash(`incl:${key}:${unitId}`) % 100 >= rollout) {
return { variant: control, inExperiment: false };
}
// Hash 2: which variant
const bucket = hash(`${key}:${unitId}`) % 100;
let acc = 0;
for (let i = 0; i < variants.length; i++) {
acc += weights[i] ?? 0;
if (bucket < acc) return { variant: variants[i] as VariantOf<K>, inExperiment: true };
}
return { variant: control, inExperiment: true };
}

The same user now gets the same variant on every request, on any server, with no stored state. Because the experiment key is part of the input, being in variant B of one test says nothing about which group you’re in for another.

There are two hashes on purpose. One decides whether a user is in the experiment at all, the other decides which variant. When you raise the rollout from 10% to 50%, new users join and nobody who was already in moves between groups. If one hash did both jobs, raising the rollout would reshuffle people and bias the results.

The user ID itself comes from proxy.ts (called middleware.ts before Next.js 16). It sets a random uid cookie on the first visit and passes it to Server Components as a request header, because a cookie set on the response isn’t visible to the same request.

Bug 3: the CDN cached one variant

The page was cached at the CDN, and the variant wasn’t part of the cache key. Whoever hit the page first decided what everyone else saw. Almost everyone gets the same variant, and the split ends up something like 90/10 instead of 50/50.

My rule now: the server decides, the client only renders, and every variant is cached separately. For most pages the variant is picked in a Server Component and streamed inside <Suspense>, while the rest of the page stays a static shell. There’s no SDK in the browser and no anti-flicker snippet. The fallback is a placeholder with the same size, never one of the variants, so there’s no layout shift and no flicker.

For pages that should be fully static, like pricing, I run the same decide() in proxy.ts and rewrite to a prebuilt copy of the page:

proxy.ts
if (req.nextUrl.pathname === '/pricing') {
const d = decide('pricing-layout', {
unitId: uid,
isBot,
overrides: parseOverrides(overrides),
});
res = NextResponse.rewrite(new URL(`/pricing/${d.variant}`, req.url), {
request: { headers },
});
}

Each variant is built with generateStaticParams. The browser URL stays /pricing, and the CDN caches each /pricing/<variant> as a separate page. Add noindex and a canonical link to the variant routes so search engines don’t index three copies of the same page.

The things around the bugs

A few smaller habits came out of this.

Every experiment lives in one typed registry with its variants, weights, rollout, owner and expiry date. variant === 'gren' becomes a type error, and removing an experiment shows every place that still uses it. A small CI script fails the build when the weights don’t add up to 100 or an experiment is past its expiry date, so old flags get removed instead of turning into dead code.

QA can force a variant with ?exp=pricing-layout:cards. Those exposures are still logged, with isOverride: true, so analysis can drop them.

Checklist before you launch an A/B test

  • One hypothesis and one primary metric, set before launch
  • Same user always gets the same variant (hash the user ID)
  • Variant chosen on the server or edge, so no flicker
  • Exposure logged when the user sees the change, in both groups
  • Variant is part of the cache key
  • Web Vitals and errors tracked per variant
  • Flag removed once the test is over

The demo

After writing about these bugs, I built a demo where you can break a test yourself and watch it get caught: ab-testing-nextjs.vercel.app.

Each bug from this post is fixed there:

  • On the checkout page nothing is logged until half of the changed block is on screen. If you don’t scroll, you’re not counted. A tracker in the corner shows how much of the block you’ve seen.
  • The overview page shows your anonymous ID, your variant in each experiment, and the hash buckets that picked it. Reload as often as you like and it stays the same.
  • /pricing is a fully static page. The proxy picks the variant and serves a prebuilt copy, and the URL doesn’t change when you switch layouts.

My favorite part is the traffic simulator. It sends 100,000 fake visitors through the same decide() the app uses and runs a chi-square check on the result. Turn on “Inject a bug” and some users in one variant stop logging their exposure, like a new page that crashes before the event goes out. The split stops matching the weights and the check flags it as a sample ratio mismatch right away. It’s the red flag from the start of this post, in a form you can click.

It’s Next.js 16 App Router with no A/B testing vendor. The code is on GitHub, and the smaller version of the same setup is in this gist.

Further reading:


More Posts