Implement A/B testing at the edge with Vercel or Cloudflare middleware. Check for an…
- User
Implement A/B testing at the edge with Vercel or Cloudflare middleware. Check for an ab-test cookie, assign a variant randomly if missing, set the cookie, and rewrite the URL to the variant path with less than 10ms latency.
- Assistant
Implementing A/B testing with Vercel and Cloudflare middleware
Detailed code snippets will show how to check or set an
ab-testcookie, assign a random variant, and rewrite the URL to the variant path efficiently in Next.js 13 middleware and Cloudflare Worker, ensuring minimal latency with no network calls. Below are minimal edge‑side snippets that do all work in a few microseconds: read theab-testcookie, choose a variant if missing, set the cookie, and rewrite the request to the variant path (e.g./a/...or/b/...). No upstream calls, so latency stays well under 10 ms.
Vercel (Next.js Edge Middleware)
/
middleware.ts(or.js):import type { NextRequest } from 'next/server' import { NextResponse } from 'next/server' const COOKIE_NAME = 'ab-test' const COOKIE_MAX_AGE = 60 * 60 * 24 * 30 // 30 days const variants = ['a', 'b'] as const export function middleware(req: NextRequest) { const url = req.nextUrl.clone() // Parse existing cookie const existing = req.cookies.get(COOKIE_NAME)?.value let variant: (typeof variants)[number] = (existing === 'a' || existing === 'b') ? existing : variants[Math.random() < 0.5 ? 0 : 1] // Rewrite path to include the variant prefix // e.g., /page -> /a/page or /b/page url.pathname = `/${variant}${url.pathname}` const res = NextResponse.rewrite(url) // Set the cookie if missing if (!existing) { res.cookies.set({ name: COOKIE_NAME, value: variant, maxAge: COOKIE_MAX_AGE, path: '/', sameSite: 'lax', }) } return res } // Exclude static assets and API routes from the A/B rewrite. export const config = { matcher: ['/((?!_next|api|favicon.ico|robots.txt|sitemap.xml).*)'], }Place your variant pages under
/a/...and/b/..., or adapturl.pathnameto your desired variant paths.
Cloudflare Workers (Middleware Style)
export default { async fetch(request: Request): Promise<Response> { const COOKIE_NAME = 'ab-test' const COOKIE_MAX_AGE = 60 * 60 * 24 * 30 // 30 days const variants = ['a', 'b'] as const const url = new URL(request.url) const cookies = Object.fromEntries( (request.headers.get('Cookie') || '') .split(';') .map(c => c.trim().split('=')) .filter(([k, v]) => k && v) ) let variant: (typeof variants)[number] = cookies[COOKIE_NAME] === 'a' || cookies[COOKIE_NAME] === 'b' ? (cookies[COOKIE_NAME] as any) : variants[Math.random() < 0.5 ? 0 : 1] // Rewrite path to variant path url.pathname = `/${variant}${url.pathname}` // Forward to the rewritten URL const response = await fetch(new Request(url.toString(), request)) // If cookie is missing, set it on the way back if (!cookies[COOKIE_NAME]) { const newHeaders = new Headers(response.headers) newHeaders.append( 'Set-Cookie', `${COOKIE_NAME}=${variant}; Max-Age=${COOKIE_MAX_AGE}; Path=/; SameSite=Lax` ) return new Response(response.body, { status: response.status, statusText: response.statusText, headers: newHeaders, }) } return response }, }Place your variant content under
/a/...and/b/.... If you already have a routing convention (e.g.,/variant-a/...), adjusturl.pathnameaccordingly.
Notes for low latency (<10 ms):
- Do all logic in the edge runtime (no network/database calls).
- Keep cookie parsing lightweight and avoid extra awaits in the middleware path.
- Exclude static assets and API routes from rewrites to avoid unnecessary work.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.