Implement A/B Testing
React Bricks A/B Testing is configured in the CMS using page variants and weights. In code, your project needs to resolve the active variant for each request and pass that information to the page rendering and analytics layers.
Use this page when you are implementing the developer side of A/B Testing and Multischeduling.
Middleware helpers
Section titled “Middleware helpers”React Bricks provides two middleware helpers:
createAbTestingMiddlewarefor Next.js Pages and Astro projectscreateWithAbTestingMiddlewarefor Next.js App projects where A/B Testing must be chained with the i18n middleware
The middleware resolves which variant should be served for the current request.
The selected variant is stored in a cookie, so a visitor keeps seeing the same variant across requests.
Recommended flow
Section titled “Recommended flow”- Configure variants and weights in React Bricks.
- Add the appropriate A/B Testing middleware helper to your project.
- Read the selected variant from cookies in your page route.
- Pass the variant name to
fetchPage. - Send the test name and variant name to your analytics provider.
Fetch the stable variant
Section titled “Fetch the stable variant”In server-rendered routes, use getAbTestingCookie to read the variant selected by the middleware, then pass it to fetchPage as variantName.
import { cookies } from 'next/headers'import { fetchPage, getAbTestingCookie, types } from 'react-bricks/rsc'
import config from '@/react-bricks/config'
const getData = async ( slug: string | string[] | undefined, locale: string): Promise<{ page: types.Page | null variantName?: string testName?: string}> => { const cleanSlug = !slug ? '/' : typeof slug === 'string' ? slug : slug.join('/')
const cookieStore = await cookies() const variantName = getAbTestingCookie({ slug: cleanSlug, locale, cookieStore, })
const page = await fetchPage({ slug: cleanSlug, language: locale, variantName, config, fetchOptions: { next: { revalidate: 3 } }, }).catch(() => null)
return { page, variantName, testName: `${cleanSlug}_${locale}`, }}Then use the same variantName when tracking the experiment:
{ testName && variantName && ( <GAExperimentTracker testName={testName} variantName={variantName} /> )}Analytics
Section titled “Analytics”React Bricks resolves the active variant, but your analytics setup decides how to track impressions and conversions.
The usual analytics flow is:
- track an impression when a variant is rendered
- track conversion events with the same test and variant identifiers
- compare conversion rates in your analytics provider
The starter projects include middleware and analytics examples on the ab-testing branch:
https://github.com/ReactBricks/reactbricks-starters/tree/feature/ab-testing/apps