09 / 10

How would you implement A/B testing using Next.js middleware and routing?

Difficulty: 5/10
Next.js middleware, routing, A/B testing

Implement A/B testing in Next.js by using middleware to assign users to variants based on cookies, deterministic hashing, or random assignment, then using NextResponse.rewrite to serve different page versions while keeping the original URL unchanged

A/B testing in Next.js using middleware and routing allows you to serve different page variants to users at the edge, without rebuilding your application or causing visible URL changes. The core pattern involves intercepting requests in middleware, assigning users to experiment variants (either randomly or deterministically), storing that assignment in a cookie for consistency, and using NextResponse.rewrite() to serve content from variant-specific routes while preserving the original URL in the browser. This approach ensures users have a consistent experience across sessions and allows you to measure conversion differences between variants .

Basic A/B Testing Middleware

To support multiple variants, organize your pages in variant-specific folders. For a homepage test, you might have a control page at app/page.tsx and a test variant at app/test/page.tsx. For more complex experiments involving multiple pages, you can create variant-specific route groups like app/(control)/ and app/(test)/ that contain entire parallel page structures. The middleware then rewrites to the appropriate group based on assignment .

Multi-Page Experiment Structure

For experiments where you want consistent assignment without relying on cookies (e.g., for SEO testing or first visits), you can use deterministic hashing based on user identifiers. This approach hashes the user ID or IP address combined with the experiment ID to produce a consistent variant assignment . This ensures users always see the same variant regardless of cookie acceptance, while maintaining a predictable split percentage.

Deterministic Assignment with Hashing

A complete A/B testing solution requires tracking variant assignments. When middleware assigns a variant, you should make that information available to your analytics tools. Common approaches include: setting a cookie that client-side analytics can read, adding the variant to response headers for server-side tracking, or making a non-blocking fetch to your analytics API from middleware . The variant information should also be passed to the client via props or context so that conversion events can be attributed correctly.

Analytics Tracking in Middleware
Best Practices for A/B Testing with Middleware
  1. 1

    Use rewrites, not redirects: Redirects change the URL and break the user's expectation—rewrites keep the URL consistent while serving different content .

  2. 2

    Store assignments in HttpOnly cookies: This prevents client-side tampering while maintaining consistency across sessions .

  3. 3

    Handle bots and crawlers: Consider excluding known bots from experiments or always showing the control variant to avoid skewed data .

  4. 4

    Implement a kill switch: Have a way to immediately show control to all users if the test variant has issues .

  5. 5

    Test with force parameters: Add support for ?force_variant=test query parameters to allow QA and internal testing .

  6. 6

    Monitor performance: Middleware must be fast—avoid blocking calls to external experiment services .

For production A/B testing, the Vercel Flags SDK provides a robust foundation . It handles variant assignment, cookie management, and integrates with popular providers. The SDK also supports precomputation for static sites, where multiple versions of pages are built at deploy time and served based on flags . This approach gives you the performance of static generation with the flexibility of runtime experiments.

Scenario Questions

0-2 years experience

  1. 1Suppose you need to split traffic 50/50 between two landing page variants using Next.js middleware. How would you set up the middleware to assign users to a variant and ensure they see the same variant on subsequent requests?
  2. 2If you add a cookie in the middleware to remember a user's bucket, what happens when the cookie is missing or malformed, and how would you handle it?
  3. 3How would you test locally that your middleware correctly redirects to the right variant?

2-5 years experience

  1. 1You added A/B testing middleware but noticed some users are getting 404 errors on the variant pages. Walk me through how you'd debug the routing logic.
  2. 2Explain the trade‑offs between using cookies versus URL query parameters to persist the bucket assignment in a Next.js app.
  3. 3If you need to roll out a third variant for only 10% of traffic, how would you modify the middleware without redeploying the entire application?

5-8 years experience

  1. 1Discuss how you would design the A/B testing middleware to handle millions of requests per second while keeping latency low. What caching or edge strategies would you employ?
  2. 2How would you ensure that server‑side rendered pages and static assets respect the same variant assignment, especially when using ISR?
  3. 3What edge cases could cause a user to switch variants mid‑session, and how would you guard against that in the middleware?

8+ years experience

  1. 1Imagine the company wants to migrate from a custom Next.js middleware A/B testing solution to a centralized experimentation platform. How would you plan the migration to minimize risk and maintain data continuity across teams?
  2. 2At scale, how would you coordinate A/B testing across multiple micro‑frontends built with Next.js, ensuring consistent bucket assignment and reporting?
  3. 3What governance and observability mechanisms would you put in place to monitor experiment health and prevent accidental exposure of unfinished variants across the entire product suite?

Follow-up Questions

  • What metrics would you monitor to confirm the experiment is behaving as expected?
  • If a variant introduces a performance regression, how would you detect and roll it back?
  • How would you verify that static assets and SSR pages respect the same bucket assignment?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.