Skip to content

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.

React Bricks provides two middleware helpers:

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.

  1. Configure variants and weights in React Bricks.
  2. Add the appropriate A/B Testing middleware helper to your project.
  3. Read the selected variant from cookies in your page route.
  4. Pass the variant name to fetchPage.
  5. Send the test name and variant name to your analytics provider.

In server-rendered routes, use getAbTestingCookie to read the variant selected by the middleware, then pass it to fetchPage as variantName.

app/[lang]/[[...slug]]/page.tsx
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} />
)
}

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