By default, Builder.io does not generate unique URLs for different A/B test variations. Instead, it uses cookies and localStorage to track and serve different variations for content analytics and testing. However, if you need unique URLs for each variation, you can fetch the variation ID and append it to the URL as a query parameter.
Solution: Override the Query Parameter with A/B Test Variation ID
If you’re using Next.js, you can modify your page component to retrieve the test variation ID and update the URL dynamically.
- Fetch the Builder.io content for the given page in
getServerSideProps
. - Extract the variation ID from Builder’s cookies using
builder.getCookie()
. - Update the URL with the test variation ID when the page content loads.
import React from "react";
import { useRouter } from "next/router";
import { BuilderComponent, builder, useIsPreviewing } from "@builder.io/react";
import DefaultErrorPage from "next/error";
import Head from "next/head";
import { BuilderContent } from "@builder.io/sdk";
import { GetServerSideProps } from "next";
import "../builder-registry";
builder.init(process.env.NEXT_PUBLIC_BUILDER_API_KEY!);
export const getServerSideProps: GetServerSideProps = async ({ params }) => {
const page = await builder
.get("page", {
userAttributes: {
urlPath: "/" + ((params?.page as string[])?.join("/") || ""),
},
})
.toPromise();
return {
props: {
page: page || null,
},
};
};
export default function Page({ page }: { page: BuilderContent | null }) {
const router = useRouter();
const isPreviewing = useIsPreviewing();
if (!page && !isPreviewing) {
return <DefaultErrorPage statusCode={404} />;
}
return (
<>
<Head>
<title>{page?.data?.title}</title>
</Head>
<BuilderComponent
model="page"
key={router.asPath}
contentLoaded={(data, content) => {
const { testVariationId } = getContentWithInfo(content);
if (!isPreviewing) {
router.replace({
pathname: content.data.url,
query: { testVariationId },
});
}
}}
content={page || undefined}
/>
</>
);
}
export const getContentWithInfo = (content?: BuilderContent) => {
if (content) {
const cookieValue = builder.getCookie(`builder.tests.${content.id}`);
const cookieVariation =
cookieValue === content.id ? content : content.variations?.[cookieValue];
return {
testVariationId: cookieValue,
testVariationName: cookieVariation?.name || "Default Variation",
};
}
return null;
};
- When a user visits the page, the
testVariationId
will be fetched and appended to the URL as a query parameter. - This ensures that each A/B test variation has a unique URL that can be shared or tracked separately.
Hope this helps!
Thanks,