Run Storyblok experiments
Set up Storyblok A/B testing in Next.js middleware
This guide buckets visitors into Storyblok Experiments and rewrites each assignment, control included, to a dedicated route without changing the URL a visitor sees. See the Storyblok API reference for the export catalog.
Install the experiment dependency
npm install @octopus-energy/flags @storyblok/experimentsCreate the experiments source
The source fetches the experiments published in your Storyblok space. Keep it at module scope so the middleware has fixed configuration.
// storyblok-experiments.ts
import { createStoryblokExperimentsSource } from "@octopus-energy/flags/storyblok";
export const experimentsSource = createStoryblokExperimentsSource({
token: process.env.STORYBLOK_TOKEN!,
});Provide a visitor identity
Choose the identity policy for this experiment before creating middleware.
Visitor cookie identity gives a
stable assignment; request identity
is stateless and rotates with the root salt. Export the selected identity as
visitorIdentity.
Request identity also needs its root-salt source configured in every runtime module graph that evaluates it. Keep that setup reusable so the proxy can initialize its own package instance:
// visitor-identity.ts
import { get } from "@vercel/global-config";
import {
createVisitorRequestIdentity,
setSaltBucketingConfig,
} from "@octopus-energy/flags/identity";
export function bootstrapVisitorRequestIdentity() {
setSaltBucketingConfig({
getRootSalt: () => get<string>("ab-testing-root-salt"),
onSaltMissing: (error) => console.error(error),
});
}
export const visitorIdentity = createVisitorRequestIdentity();Cookie identity does not need this salt bootstrap.
Create the middleware
Configure paths that must not participate, the Storyblok slug for the home page when applicable, and the internal route that renders each assignment. Locale prefixes are optional; see Localised routes.
// proxy.ts
import { createStoryblokExperimentsMiddleware } from "@octopus-energy/flags/storyblok";
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { experimentsSource } from "./storyblok-experiments";
import { bootstrapVisitorRequestIdentity, visitorIdentity } from "./visitor-identity";
// Next.js compiles proxy into an isolated module graph. Bootstrap request
// identity here: configuring it only in instrumentation may initialize a
// different package instance and make every request serve control.
bootstrapVisitorRequestIdentity();
const storyblokMiddleware = createStoryblokExperimentsMiddleware({
experimentsSource,
identity: visitorIdentity,
skipPathPrefixes: ["/api", "/dashboard"],
rootSlug: "home",
routing: {
rewritePathname: ({ experimentName, variantName, resolvedStoryblokSlug }) =>
`/experiments/${experimentName}/${variantName}/${resolvedStoryblokSlug}`,
},
});
export async function proxy(request: NextRequest) {
// Middleware rewrites are not re-run through middleware, so only direct
// requests for the internal route reach this check.
if (request.nextUrl.pathname.startsWith("/experiments/")) {
return new NextResponse(null, { status: 404 });
}
const storyblok = await storyblokMiddleware(request);
return storyblok.response();
}Use the same code in middleware.ts, with an exported middleware function,
when that is the convention in your Next.js application.
Every assigned visitor is rewritten to routing.rewritePathname. A visitor on
/blog/test assigned to bold in hero_test is served
/experiments/hero_test/bold/blog/test-hero_test-bold, and one assigned to
control is served /experiments/hero_test/control/blog/test, while the URL stays
/blog/test. Visitors who cannot be assigned, such as when identity or
experiment data is unavailable, are served the public page unchanged. Rejecting
direct requests keeps the internal route unreachable, so its params can be
trusted as the visitor's assignment.
rewritePathname receives:
pathname: the destination pathname produced by earlier middleware, so locale or application rewrites can be preserved.locale: thelocalePrefixesentry matched on the request pathname (for example"de"), orundefinedwhen none matched or nolocalePrefixesare configured.experimentNameandvariantName: the technical names of the experiment and the assigned variant.isControl: whether the assigned variant is the experiment's control. Use it instead of the control's technical name, which is set in Storyblok.resolvedStoryblokSlug: the full slug of the story to render, for exampleblog/test-hero_test-bold, or the original story's slug for control.
The package retains the origin, query parameters, and response metadata. The
Storyblok source slug is derived from the request pathname, without any locale
prefix and with / mapped to rootSlug. Set routing.storyblokSlug only when
the experimented story differs from the page URL; see
Experiment an embedded story.
A request for a variant story's own URL, such as /blog/test-hero_test-bold,
is redirected (307) to the original story's URL, /blog/test, keeping any
locale prefix and the query string. The visitor is then bucketed there, so a
shared or indexed variant link cannot bypass assignment. The Storyblok editor
and draft mode still load variant stories directly.
Localised routes
Locale handling is optional; leave localePrefixes unset when your URLs carry
no locale. When they do, list the prefixes: the middleware strips the matched
prefix before deriving the Storyblok slug, keeps it on variant redirects, and
passes it to rewritePathname as locale. Use it to keep the prefix on the
internal route, for example when the dedicated route lives under an
app/[locale] segment:
const defaultLocale = "en";
const storyblokMiddleware = createStoryblokExperimentsMiddleware({
experimentsSource,
identity: visitorIdentity,
localePrefixes: ["en", "de"],
routing: {
// `locale` is undefined for unprefixed URLs, such as the default locale
// with next-intl's `localePrefix: "as-needed"`.
rewritePathname: ({ locale, experimentName, variantName, resolvedStoryblokSlug }) =>
`/${locale ?? defaultLocale}/experiments/${experimentName}/${variantName}/${resolvedStoryblokSlug}`,
},
});Reject direct requests for the localised internal route as well, for example
by matching /^(\/(en|de))?\/experiments\// in the proxy.
Render assignments on the dedicated route
The dedicated route renders the story named by its slug param, the variant story
or the original story for control, and receives the experiment and variant as
route params. With localised routes, nest it under your locale segment, for
example app/[locale]/experiments/[experiment]/[variant]/[...slug]/page.tsx.
// app/experiments/[experiment]/[variant]/[...slug]/page.tsx
import { ExperimentExposureReporter } from "@octopus-energy/flags/reporting";
import { notFound } from "next/navigation";
// Or use Next's typedRoutes: PageProps utility type
type Params = { experiment: string; variant: string; slug: string[] };
export default async function ExperimentPage({ params }: { params: Promise<Params> }) {
const { experiment, variant, slug } = await params;
// Fetch the variant story, or the original story for control.
const story = await fetchStory(slug.join("/"));
if (!story) notFound();
return (
<>
<ExperimentExposureReporter exposures={[{ experimentId: experiment, variantId: variant }]} />
<StoryPage story={story} />
</>
);
}Report exposures only from the dedicated route, using its experiment and
variant params. The public route serves visitors who could not be assigned,
so it should not report an exposure.
Experiment an embedded story
When only part of a page comes from Storyblok, set routing.storyblokSlug to
the embedded story and rewrite to an internal route that renders it inside the
page. It is required here: without it the slug comes from the pathname
(meter-optimisation/adaptee), which does not match the embedded story. The
function form maps each embedding page to its story, so one middleware can
serve several of them; returning undefined skips every other request.
// Embedding page path to the Storyblok story it embeds.
const embeddedStories: Record<string, string> = {
"/meter-optimisation/adaptee": "meter-optimisation/adaptee-content",
"/smart-meters/installation": "smart-meters/installation-content",
};
const storyblokMiddleware = createStoryblokExperimentsMiddleware({
experimentsSource,
identity: visitorIdentity,
routing: {
storyblokSlug: (request) => embeddedStories[request.nextUrl.pathname],
rewritePathname({ pathname, experimentName, variantName }) {
return `${pathname}/__experiment/${experimentName}/${variantName}`;
},
},
});request.nextUrl.pathname includes any locale prefix, so strip it before the
lookup if your routes are localised.
Under each embedding page, add a dynamic internal route such as
adaptee/__experiment/[experiment]/[variant].tsx, resolve the variant's
Storyblok story, or the original story for control, in getStaticProps, and
report the exposure from the experiment and variant params. Generate every
experiment and variant pair, control included, with getStaticPaths, and
consider fallback: "blocking" when experiments can gain variants without a
new deployment. Keep the public page as the fail-open route for visitors who
cannot be assigned.
A string storyblokSlug, such as "meter-optimisation/adaptee-content", is
matched for every request that reaches the middleware, regardless of path. As
the only Storyblok middleware it would bucket and rewrite the whole site, so
use a string only when this middleware runs for the embedding page alone, for
example when your proxy selects a middleware instance per path.
Set the canonical URL
A rewrite serves an assignment at the original URL, but the dedicated route
receives the variant story's slug, such as blog/test-hero_test-bold, in its
route params. A canonical URL built from those params points crawlers at the
variant URL, which redirects back to the original. Add a
<link rel="canonical"> that always names the original story's public URL, so
the original page is indexed whichever assignment a crawler is served.
Map the rendered slug back to its original with getCanonicalSlug(slug, experiments). A variant story's slug returns its original story's slug; any
other slug, including the original story served to control, is returned
unchanged. Set it from generateMetadata in every route that renders Storyblok
stories: your public route and the dedicated route, never /experiments/.... A
relative canonical resolves against metadataBase in your root layout.
// app/experiments/[experiment]/[variant]/[...slug]/page.tsx
import type { Metadata } from "next";
import { getCanonicalSlug } from "@octopus-energy/flags/storyblok";
import { experimentsSource } from "@/storyblok-experiments";
import { cacheTag } from "next/cache";
async function getCachedExperiments() {
"use cache";
cacheTag("storyblok-experiments");
// Fail open: without experiment data, the rendered slug is the best canonical.
return await experimentsSource().catch(() => []);
}
export async function generateMetadata({
params,
}: {
params: Promise<{ slug: string[] }>;
}): Promise<Metadata> {
const { slug } = await params;
// Experiment source deliberately skips Storyblok caching.
// Cache appropriately to avoid re-fetching on every render
const experiments = await getCachedExperiments();
const canonicalSlug = getCanonicalSlug(slug.join("/"), experiments);
return { alternates: { canonical: `/${canonicalSlug}` } };
}Map your rootSlug story to /, and prefix the locale if your routes are
localised, the same way your public routes do. With the Pages Router, render
the same URL as <link rel="canonical" href={canonicalUrl} /> inside
next/head. For an embedded story, the canonical URL is the public page that
embeds it, such as /meter-optimisation/adaptee, rather than a URL derived from
the story slug.