TL;DR: Avoid UI flicker and layout shift in Next.js A/B tests by deciding the variant before the HTML is generated. A CloudFront Function on the viewer request assigns the
ab_variantcookie when it is missing, the CloudFront cache policy keys the cache on that one cookie, and Next.js Proxy (called Middleware before Next.js 16) rewrites the request to a statically generated variant route. Each variant is cached once at the edge instead of once per visitor.
Key Takeaways
- Avoid client-side variant swapping with
useEffectand feature flag SDKs, which shows a placeholder or the wrong variant before the right one appears. - Use a CloudFront cache policy that includes only the
ab_variantcookie in the cache key, so tracking cookies such as_gado not fragment the cache. - Assign the variant in a CloudFront Function on the viewer request, not only at the origin. CloudFront caches
Set-Cookieheaders with the object, so an origin-assigned cookie on a shared cache entry would be replayed to every new visitor. - Use Next.js Proxy (
proxy.ts, formerlymiddleware.ts) to read the cookie and rewrite/to the matching variant route without changing the URL. - Pre-render the variants with
generateStaticParams, and point their canonical URL at/so search engines see one page.
You launch an A/B test. The user navigates to the landing page, the hero section loads in the default blue, and a moment later it switches to the experimental red variant.
That flash is visible to users, it can add Cumulative Layout Shift (CLS) if the variants differ in size, and it can delay Largest Contentful Paint (LCP) when the hero is hidden until the variant is known. It is a common side effect of client-side personalization in server-rendered applications.
Traditional A/B testing SDKs rely on the browser to fetch feature flags, evaluate targeting rules, and swap out React components. In a Next.js App Router application, that means either rendering a placeholder until the client knows the variant or risking a hydration mismatch. Moving the decision to the origin server fixes the flicker, but if every request carries unique cookies, the CDN can no longer cache the page and every request reaches your servers.
The approach in this guide pushes variant assignment to the CDN edge and keeps the pages static. AWS CloudFront Functions assign and normalize the variant cookie, and Next.js Proxy rewrites the request to a pre-rendered variant, so each variant is served from the CDN cache like any static page.
Why Client-Side A/B Testing Flickers
To understand why edge routing helps, look at the standard client-side implementation most teams start with:
// Anti-pattern: client-side variant swapping
'use client';
import { useEffect, useState } from 'react';
import { useFeatureFlags } from '@thirdparty/sdk';
import HeroRed from './HeroRed';
import HeroBlue from './HeroBlue';
export default function HeroSection() {
const [mounted, setMounted] = useState(false);
const { variant } = useFeatureFlags('hero_test_v1');
useEffect(() => {
setMounted(true);
}, []);
// Prevents hydration mismatch, but forces a blank state or delayed render
if (!mounted) return <div className="h-96 bg-gray-100 animate-pulse" />;
return variant === 'treatment' ? <HeroRed /> : <HeroBlue />;
}
This approach forces the client to download the JavaScript bundle, hydrate React, run the useEffect hook, wait for flags, and re-render. In the best case the user sees a loading skeleton in the hero position; in the worst case they see the control variant before the treatment replaces it. Measure the effect on your own pages with the Web Vitals report or real-user monitoring, and see our Next.js App Router performance checklist for the wider set of Core Web Vitals fixes.
Edge-Driven Personalization Architecture
To fix this, we split the responsibilities between the CDN edge and the Next.js application server:
- CloudFront Function (viewer request): Reads the
ab_variantcookie. If it is missing or invalid, assigns a variant. Forwards only that cookie. - CloudFront cache policy: Includes only
ab_variantin the cache key, so there is one cache entry per variant (per URL), not one per visitor. - Next.js Proxy: Reads the cookie, rewrites
/to/controlor/treatment, and sets the cookie on the response so the browser keeps the same variant. - Next.js App Router: Statically generates all variants at build time using
generateStaticParams.
Production Note: Why CloudFront Functions instead of Lambda@Edge? CloudFront Functions run in a lightweight JavaScript runtime at every edge location, are built for short request and header manipulation, and are billed per invocation with no duration charge. Lambda@Edge is billed per request plus duration and is better suited to work that needs network calls or a larger runtime. Check the CloudFront and Lambda pricing pages for current per-million prices in your account.
Phase 1: Assigning and Normalizing the Variant at the Edge
By default, forwarding the whole Cookie header to your Next.js origin and including it in the cache key ruins your CDN cache hit rate. Every visitor has unique tracking cookies (like _ga or _fbp), so CloudFront would treat almost every request as a new cache key.
There is a second, less obvious problem. If the origin assigns the variant and responds with Set-Cookie, CloudFront caches that Set-Cookie header together with the object and sends it to every viewer who gets that cached response. If the first cookieless visitor was assigned treatment, every later cookieless visitor would receive the cached treatment page and the same cookie, and your split would collapse to 100/0.
The fix is to make sure no request reaches the cache without a variant. A CloudFront Function on the viewer request event assigns one when the cookie is missing and drops every other cookie:
// cloudfront-function-viewer-request.js (cloudfront-js-2.0 runtime)
var VARIANTS = ['control', 'treatment'];
function handler(event) {
var request = event.request;
var existing = request.cookies['ab_variant'];
var variant = existing && existing.value;
// Assign a variant at the edge so the cache key always contains one
if (VARIANTS.indexOf(variant) === -1) {
variant = Math.random() < 0.5 ? 'control' : 'treatment';
}
// Replace all cookies with just the variant cookie.
// CloudFront Functions expose cookies in request.cookies, not in request.headers.
request.cookies = { ab_variant: { value: variant } };
return request;
}
Next, configure the CloudFront cache policy to include only the ab_variant cookie in the cache key. Here is the Terraform snippet:
# terraform/cloudfront.tf
resource "aws_cloudfront_cache_policy" "nextjs_ab_testing" {
name = "Nextjs-AB-Testing-Policy"
default_ttl = 86400
max_ttl = 31536000
min_ttl = 0
parameters_in_cache_key_and_forwarded_to_origin {
cookies_config {
cookie_behavior = "whitelist"
cookies {
items = ["ab_variant"]
}
}
headers_config {
header_behavior = "none"
}
query_strings_config {
query_string_behavior = "none"
}
}
}
Only include headers and query strings that actually change the HTML. Adding query_string_behavior = "all" means every utm_ or gclid parameter creates a new cache entry. If your origin needs the original Host header, forward it with an origin request policy rather than adding it to the cache key.
Phase 2: Next.js Proxy for Transparent Routing
When the request reaches Next.js, Proxy intercepts it. In Next.js 16 the middleware.ts file convention was renamed to proxy.ts and the exported function to proxy; the behavior is the same, and Proxy now runs on the Node.js runtime by default. If you are still on Next.js 15, use middleware.ts and export function middleware. Our Next.js 16 migration guide covers the rename.
Proxy reads the cookie, rewrites / to the internal variant route, and writes the cookie back on the response. The assignment fallback only matters when requests do not pass through CloudFront, such as in local development.
// proxy.ts (project root, next to the app directory)
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
const COOKIE_NAME = 'ab_variant';
const VARIANTS = ['control', 'treatment'] as const;
type Variant = (typeof VARIANTS)[number];
function isVariant(value: string | undefined): value is Variant {
return VARIANTS.includes(value as Variant);
}
export function proxy(request: NextRequest) {
const cookieValue = request.cookies.get(COOKIE_NAME)?.value;
// CloudFront assigns the variant in production; this fallback covers local development
const variant: Variant = isVariant(cookieValue)
? cookieValue
: Math.random() < 0.5
? 'control'
: 'treatment';
const url = request.nextUrl.clone();
url.pathname = `/${variant}`;
const response = NextResponse.rewrite(url);
// Safe to cache: the cache key already contains this exact variant
response.cookies.set(COOKIE_NAME, variant, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: 60 * 60 * 24 * 30, // 30 days
});
return response;
}
// Only run on the page under test
export const config = {
matcher: '/',
};
Because the response sets the same variant that is already in the cache key, it does not matter that CloudFront caches the Set-Cookie header: every viewer who hits the treatment cache entry already has, or was just assigned, ab_variant=treatment. The matcher keeps Proxy off static assets and API routes without string checks in the function body.
Warning: Use
NextResponse.rewrite(), notNextResponse.redirect(). A redirect changes the URL in the user's browser and adds a round trip. A rewrite keeps the URL identical (e.g.,yourapp.com/) while internally serving the/[variant]content.
Phase 3: Statically Generating the App Router Variants
We want the performance of Static Site Generation (SSG) with per-visitor variants. We achieve this by mapping the rewritten paths to a dynamic route segment in the App Router. Next.js ignores route groups (folders wrapped in parentheses) in the URL path, which keeps the variant pages organized.
Structure your project like this. Note that proxy.ts lives at the project root (or in src/), not inside app/:
proxy.ts
app/
├── (variants)/
│ └── [variant]/
│ ├── page.tsx
│ └── layout.tsx
└── layout.tsx
In app/(variants)/[variant]/page.tsx, use generateStaticParams to build both the control and treatment pages as static HTML at build time, and set dynamicParams = false so any other value returns a 404.
// app/(variants)/[variant]/page.tsx
import type { Metadata } from 'next';
import HeroControl from '@/components/HeroControl';
import HeroTreatment from '@/components/HeroTreatment';
import AnalyticsTracker from '@/components/AnalyticsTracker';
interface PageProps {
// params is a Promise in Next.js 15 and later
params: Promise<{ variant: string }>;
}
// Only the listed variants exist; anything else is a 404
export const dynamicParams = false;
export function generateStaticParams() {
return [{ variant: 'control' }, { variant: 'treatment' }];
}
// Both variants describe the same page, so they share one canonical URL
export const metadata: Metadata = {
alternates: { canonical: '/' },
};
export default async function LandingPage({ params }: PageProps) {
const { variant } = await params;
return (
<main className="flex min-h-screen flex-col items-center">
{/* The variant is decided before this HTML is generated, so there is no swap */}
{variant === 'treatment' ? <HeroTreatment /> : <HeroControl />}
<section className="mt-10">
<h2>Shared Content Below the Fold</h2>
<p>This content remains the same across both variants.</p>
</section>
<AnalyticsTracker variant={variant} />
</main>
);
}
Because CloudFront caches the response per ab_variant value, a visitor assigned to treatment gets the pre-rendered treatment HTML from the edge cache after the first request for that variant. The browser receives the final markup in the first response, so there is nothing to swap after hydration.
Handling Edge Cases: Search Engines, Analytics and Caching
Edge personalization introduces failure modes that can hurt SEO or serve the wrong variant if left unchecked.
1. Search Engines and Cloaking
It is tempting to detect crawlers by user agent and always serve them the control. Google's guidance on website testing says not to do this: showing Googlebot different content from humans is cloaking, whether or not you are running a test, and it counts regardless of whether it is done by server logic or another method. Treat crawlers like any other cookieless visitor instead.
Google also notes that Googlebot generally does not support cookies, so it will see whichever variant a cookieless visitor receives. With edge assignment, that can differ between crawls. To keep this safe:
- Keep the core content, title and headings the same across variants and test presentation, layout or calls to action.
- Point both variant routes at one canonical URL, as the
metadataexport above does. - Run the test only as long as you need for a statistically meaningful result, then remove the losing variant.
You can still use userAgent(request).isBot from next/server to exclude known bots from your experiment analytics, as long as it does not change the content they receive.
2. Analytics Integration
A common issue with server-side A/B testing is connecting the assigned variant to your client-side analytics (e.g., Google Analytics 4, Mixpanel, Segment). Because the cookie is httpOnly, client scripts cannot read it, and they should not need to: the variant is already known when the page is rendered.
Pass it to a small Client Component that records the exposure on mount:
// components/AnalyticsTracker.tsx
'use client';
import { useEffect } from 'react';
declare global {
interface Window {
dataLayer?: Record<string, unknown>[];
}
}
export default function AnalyticsTracker({ variant }: { variant: string }) {
useEffect(() => {
// Push to the Google Tag Manager data layer (created here if GTM has not loaded yet)
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
event: 'ab_test_exposure',
test_name: 'hero_conversion_test',
variant_assigned: variant,
});
}, [variant]);
return null;
}
The page component above already renders <AnalyticsTracker variant={variant} />, so every exposure is recorded with the variant that was actually shown.
3. Avoiding Mixed-Up Cache Entries
If the CDN cache key does not include the variant, CloudFront can cache the control HTML and serve it to a treatment user. CloudFront builds its cache key from the cache policy, so the cache policy above is the control that matters. Test it before launch: request / with Cookie: ab_variant=control and with Cookie: ab_variant=treatment and confirm that each returns its own HTML and that the X-Cache header shows hits for both.
If another shared cache sits between CloudFront and Next.js, make sure it keys on the cookie as well or does not cache this route.
With variant assignment at the edge, a cache key limited to one cookie, and static variant pages behind a Proxy rewrite, users see the right variant in the first HTML response and the CDN keeps serving those pages from cache. If you are rolling this out across a larger Next.js site, our full-stack web development services cover edge caching and experimentation setups like this one.
Sources
- Amazon CloudFront Developer Guide: CloudFront Functions event structure
- Amazon CloudFront Developer Guide: Cache content based on cookies
- Next.js Docs:
proxy.jsfile convention - Next.js Docs:
generateStaticParams - Google Search Central: Minimize A/B testing impact in Google Search
Need help building this in production?
SoftwareCrafting is a full-stack dev agency - we ship fast, scalable React, Next.js, Node.js, React Native & Flutter apps for global clients.
Get a Free ConsultationFrequently Asked Questions
Why does client-side A/B testing cause UI flickering in Next.js?
Client-side A/B testing makes the browser download the JavaScript bundle, hydrate React, and evaluate feature flags before rendering the correct variant. Until then, the user sees either a loading placeholder or the control variant, which then switches to the treatment. That switch is the flicker, and it can add layout shift if the variants differ in size.
How can I prevent A/B testing from destroying my CDN cache hit rate?
Include only the A/B variant cookie in the CloudFront cache key with a cache policy cookie whitelist, so tracking cookies (like Google Analytics) do not create one cache entry per visitor. A CloudFront Function on the viewer request can also drop every other cookie and assign the variant before the cache lookup.
Why should I assign the variant in a CloudFront Function rather than only at the origin?
CloudFront caches Set-Cookie headers along with the cached object and returns them on cache hits. If the origin assigns the variant for cookieless visitors, the first assignment gets cached and replayed to every later cookieless visitor. Assigning the variant at the edge before the cache lookup means every request already carries a variant, so each cache entry matches exactly one variant.
How does Next.js Proxy handle the A/B test variant?
Proxy (named Middleware before Next.js 16) intercepts the request from CloudFront, reads the ab_variant cookie, rewrites / to the matching variant route, and sets the cookie on the response so the browser keeps the same variant on later visits.
Can I use statically generated pages (SSG) with edge-based A/B testing?
Yes. Use generateStaticParams in the App Router to pre-render every variant at build time. Proxy only rewrites the request to the correct pre-rendered route, and CloudFront caches each variant separately based on the cookie in the cache key.
