Adds A/B testing to Payload v3 with Next.js. Variants are stored as documents in the same collection as the original page and given a traffic percentage in a sidebar panel. Hooks rebuild a variant manifest that middleware reads to rewrite requests without a database call. It requires Payload 3.90 or later, the companion guard plugin and a config wrapped in its access policy.
A/B testing plugin for Payload CMS
Installation
npm i @focus-reactive/payload-plugin-ab37
Stars
5
Forks
33
Open Issues
Today
Last Updated
652
Weekly Downloads
v3.0.1
npm Version
261.6 KB
Unpacked Size
1
Dependencies
37+22 since Sep 7
| Date | Stars |
|---|---|
| Dec 6, 2026 | 37 |
| Dec 5, 2026 | 37 |
| Dec 4, 2026 | 37 |
| Dec 3, 2026 | 37 |
| Dec 2, 2026 | 37 |
| Dec 1, 2026 | 36 |
| Nov 30, 2026 | 35 |
| Nov 29, 2026 | 35 |
| Nov 28, 2026 | 34 |
| Nov 27, 2026 | 34 |
| Nov 26, 2026 | 34 |
| Nov 25, 2026 | 34 |
| Nov 24, 2026 | 34 |
| Nov 23, 2026 | 34 |
| Nov 22, 2026 | 34 |
| Nov 21, 2026 | 34 |
| Nov 20, 2026 | 33 |
| Nov 19, 2026 | 32 |
| Nov 18, 2026 | 32 |
| Nov 17, 2026 | 32 |
| Nov 16, 2026 | 32 |
| Nov 15, 2026 | 32 |
| Nov 14, 2026 | 32 |
| Nov 13, 2026 | 32 |
| Nov 12, 2026 | 32 |
| Nov 11, 2026 | 32 |
| Nov 10, 2026 | 32 |
| Nov 9, 2026 | 31 |
| Nov 8, 2026 | 31 |
| Nov 7, 2026 | 31 |
| Nov 6, 2026 | 31 |
| Nov 5, 2026 | 31 |
| Nov 4, 2026 | 30 |
| Nov 3, 2026 | 30 |
| Nov 2, 2026 | 30 |
| Nov 1, 2026 | 30 |
| Oct 31, 2026 | 30 |
| Oct 30, 2026 | 30 |
| Oct 29, 2026 | 30 |
| Oct 28, 2026 | 30 |
| Oct 27, 2026 | 30 |
| Oct 26, 2026 | 30 |
| Oct 25, 2026 | 30 |
| Oct 24, 2026 | 29 |
| Oct 23, 2026 | 29 |
| Oct 22, 2026 | 29 |
| Oct 21, 2026 | 29 |
| Oct 20, 2026 | 29 |
| Oct 19, 2026 | 29 |
| Oct 18, 2026 | 29 |
| Oct 17, 2026 | 27 |
| Oct 16, 2026 | 26 |
| Oct 15, 2026 | 26 |
| Oct 14, 2026 | 26 |
| Oct 13, 2026 | 25 |
| Oct 12, 2026 | 25 |
| Oct 11, 2026 | 25 |
| Oct 10, 2026 | 25 |
| Oct 9, 2026 | 25 |
| Oct 8, 2026 | 25 |
| Oct 7, 2026 | 25 |
| Oct 6, 2026 | 24 |
| Oct 5, 2026 | 24 |
| Oct 4, 2026 | 24 |
| Oct 3, 2026 | 23 |
| Oct 2, 2026 | 22 |
| Oct 1, 2026 | 22 |
| Sep 30, 2026 | 20 |
| Sep 29, 2026 | 20 |
| Sep 28, 2026 | 20 |
| Sep 27, 2026 | 20 |
| Sep 26, 2026 | 19 |
| Sep 25, 2026 | 18 |
| Sep 24, 2026 | 18 |
| Sep 23, 2026 | 18 |
| Sep 22, 2026 | 18 |
| Sep 21, 2026 | 18 |
| Sep 20, 2026 | 18 |
| Sep 19, 2026 | 18 |
| Sep 18, 2026 | 18 |
| Sep 17, 2026 | 18 |
| Sep 16, 2026 | 18 |
| Sep 15, 2026 | 18 |
| Sep 14, 2026 | 18 |
| Sep 13, 2026 | 17 |
| Sep 12, 2026 | 17 |
| Sep 11, 2026 | 17 |
| Sep 10, 2026 | 16 |
| Sep 9, 2026 | 16 |
| Sep 8, 2026 | 16 |
| Sep 7, 2026 | 15 |
Shared by 15 plugins in focusreactive/payload-plugins.
652+529 since Sep 7
| Date | Weekly downloads |
|---|---|
| Dec 6, 2026 | 652 |
| Dec 5, 2026 | 658 |
| Dec 4, 2026 | 664 |
| Dec 3, 2026 | 682 |
| Dec 2, 2026 | 642 |
| Dec 1, 2026 | 616 |
| Nov 30, 2026 | 587 |
| Nov 29, 2026 | 412 |
| Nov 28, 2026 | 358 |
| Nov 27, 2026 | 345 |
| Nov 26, 2026 | 510 |
| Nov 25, 2026 | 512 |
| Nov 24, 2026 | 535 |
| Nov 23, 2026 | 578 |
| Nov 22, 2026 | 556 |
| Nov 21, 2026 | 578 |
| Nov 20, 2026 | 614 |
| Nov 19, 2026 | 445 |
| Nov 18, 2026 | 568 |
| Nov 17, 2026 | 552 |
| Nov 16, 2026 | 508 |
| Nov 15, 2026 | 605 |
| Nov 14, 2026 | 693 |
| Nov 13, 2026 | 641 |
| Nov 12, 2026 | 643 |
| Nov 11, 2026 | 689 |
| Nov 10, 2026 | 732 |
| Nov 9, 2026 | 843 |
| Nov 8, 2026 | 803 |
| Nov 7, 2026 | 715 |
| Nov 6, 2026 | 723 |
| Nov 5, 2026 | 734 |
| Nov 4, 2026 | 539 |
| Nov 3, 2026 | 504 |
| Nov 2, 2026 | 546 |
| Nov 1, 2026 | 547 |
| Oct 31, 2026 | 533 |
| Oct 30, 2026 | 535 |
| Oct 29, 2026 | 419 |
| Oct 28, 2026 | 388 |
| Oct 27, 2026 | 407 |
| Oct 26, 2026 | 276 |
| Oct 25, 2026 | 245 |
| Oct 24, 2026 | 261 |
| Oct 23, 2026 | 186 |
| Oct 22, 2026 | 235 |
| Oct 21, 2026 | 254 |
| Oct 20, 2026 | 223 |
| Oct 19, 2026 | 204 |
| Oct 18, 2026 | 221 |
| Oct 17, 2026 | 187 |
| Oct 16, 2026 | 273 |
| Oct 15, 2026 | 424 |
| Oct 14, 2026 | 522 |
| Oct 13, 2026 | 526 |
| Oct 12, 2026 | 518 |
| Oct 11, 2026 | 514 |
| Oct 10, 2026 | 538 |
| Oct 9, 2026 | 474 |
| Oct 8, 2026 | 331 |
| Oct 7, 2026 | 295 |
| Oct 6, 2026 | 314 |
| Oct 5, 2026 | 635 |
| Oct 4, 2026 | 647 |
| Oct 3, 2026 | 706 |
| Oct 2, 2026 | 707 |
| Oct 1, 2026 | 733 |
| Sep 30, 2026 | 714 |
| Sep 29, 2026 | 708 |
| Sep 28, 2026 | 393 |
| Sep 27, 2026 | 347 |
| Sep 26, 2026 | 264 |
| Sep 25, 2026 | 263 |
| Sep 24, 2026 | 190 |
| Sep 23, 2026 | 151 |
| Sep 22, 2026 | 137 |
| Sep 21, 2026 | 165 |
| Sep 20, 2026 | 159 |
| Sep 19, 2026 | 240 |
| Sep 18, 2026 | 252 |
| Sep 17, 2026 | 341 |
| Sep 16, 2026 | 364 |
| Sep 15, 2026 | 383 |
| Sep 14, 2026 | 348 |
| Sep 13, 2026 | 351 |
| Sep 12, 2026 | 256 |
| Sep 11, 2026 | 250 |
| Sep 10, 2026 | 170 |
| Sep 9, 2026 | 147 |
| Sep 8, 2026 | 122 |
| Sep 7, 2026 | 123 |
Each point is npm's rolling 7-day download count.
Health Score
Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.
Badge for your README
[](https://payloaddirectory.dev/plugins/1177993877-payload-plugin-ab)<a href="https://payloaddirectory.dev/plugins/1177993877-payload-plugin-ab"><img src="https://payloaddirectory.dev/badge/1177993877-payload-plugin-ab.svg" alt="Payload Directory"></a>README
A/B testing plugin for Payload CMS v3 + Next.js. Create page variants directly inside the Payload admin, assign traffic percentages, and route users at the edge.
Variants live in the same collection as the original page. The plugin injects the admin UI, hooks, and a variant manifest that Next.js middleware reads to route traffic without a database round-trip.
The plugin is built on @focus-reactive/payload-plugin-guard.
Your project's access policy file decides who may create variants and who may change the traffic split.
Requirements: Payload ^3.90.0, @focus-reactive/payload-plugin-guard, and a config wrapped in withAccessPolicy.
Copy and paste this prompt into your AI assistant (Cursor, Claude, etc.) to integrate the plugin into an existing Payload + Next.js project.
I want to add A/B testing to my Payload CMS v3 + Next.js project using
@focus-reactive/payload-plugin-ab. Follow these steps in order, and stop to ask me where a step says so.
## Rules you must follow
- Never write an access rule that admits every logged-in user: no `Boolean(req.user)`, no `() => true`,
no `({ req }) => !!req.user`. A rule names a role, or it is `nobody`.
The one exception is `anyone` on the manifest global's read, which the site middleware needs.
- Do not invent roles. Ask me which roles may create variants and which may change the traffic split.
- Write every policy entry by hand in `src/access.policy.ts`, and grant each capability and each
collection right explicitly to the roles I name. Nothing is open by default.
- When the boot or a request fails, fix the cause or ask me. Never use `anyone`, a looser gate,
`overrideAccess` or a removed or disabled check to make an error go away.
- Do not add `overrideAccess: true` anywhere, and do not add `access` to the plugin's collection or global.
## How it works
Variants are regular documents in the same collection as the original page, linked to it by an
injected `_abVariantOf` relationship and carrying their share of traffic in `_abPassPercentage`.
The plugin adds a Variants panel to the original page, a `POST /api/ab/variants` endpoint that copies
a page as a variant, a manifest global (`_abManifest`) that the Next.js middleware reads, and an
`ab-experiments` collection. Only the plugin writes the global and the collection.
It declares two capabilities that the project grants in its access policy:
- `createVariant`: copy a page as a variant. The caller also needs read and create rights in the
collection and update rights on the original page.
- `splitTraffic`: change a variant's share of traffic. The caller also needs update rights on the
original page.
## Step 1: install
pnpm add @focus-reactive/payload-plugin-ab @focus-reactive/payload-plugin-guard
Check that `payload` is 3.90 or later; if it is not, upgrade it first.
## Step 2: ask me about roles
Look at the auth collection named in `admin.user` and the roles it has.
Ask me: "Which roles may create A/B variants?" and "Which roles may change the traffic split?"
Wait for my answers. Write each answer as a gate in the policy file in step 3.
## Step 3: the access policy file
Open `src/access.policy.ts`, or create it if the project has none, following the guard README
(`defineAccessPolicy`, `gate`, `filter`, `nobody`, `anyone`, checked with `satisfies AccessPolicy<Config>`).
If you create it, every collection and global of the config needs an entry: move each existing
`access` of the project into the file, and ask me for every rule you cannot read from the code.
Add these entries for this plugin:
collections: {
"ab-experiments": { create: nobody, read: <a staff gate>, update: nobody, delete: nobody },
},
globals: {
_abManifest: { read: anyone, update: nobody },
},
plugins: {
ab: { createVariant: <the gate from my first answer>, splitTraffic: <the gate from my second answer> },
},
## Step 4: register the plugin and wrap the config
// payload.config.ts
import { buildConfig } from 'payload'
import { withAccessPolicy } from '@focus-reactive/payload-plugin-guard'
import { abTestingPlugin } from '@focus-reactive/payload-plugin-ab'
import { payloadGlobalAdapter } from '@focus-reactive/payload-plugin-ab/adapters/payload-global'
import { accessPolicy } from './access.policy'
const abAdapter = payloadGlobalAdapter({ serverURL: process.env.NEXT_PUBLIC_SERVER_URL ?? '' })
export default withAccessPolicy(
accessPolicy,
buildConfig({
// ...the existing config
plugins: [
abTestingPlugin({
storage: abAdapter,
access: accessPolicy.plugins.ab,
collections: {
pages: {
generatePath: ({ doc, locale }) => {
const slug = doc.slug as string | undefined
if (!slug) return null
return locale ? `/${locale}/${slug}` : `/${slug}`
},
},
},
}),
],
})
)
Run `payload generate:types`, then start the app.
A missing or wrong policy entry stops the boot with a list of what to fix.
Fix each item; never loosen a rule to make an error go away.
## Step 5: Next.js middleware
import { NextResponse } from 'next/server'
import { createResolveAbRewrite } from '@focus-reactive/payload-plugin-ab/middleware'
import { payloadGlobalAdapter } from '@focus-reactive/payload-plugin-ab/adapters/payload-global'
const storage = payloadGlobalAdapter({ serverURL: process.env.NEXT_PUBLIC_SERVER_URL ?? '' })
const resolveAbRewrite = createResolveAbRewrite({
storage,
getBucket: (v) => v.bucket,
getRewritePath: (v) => v.rewritePath,
getPassPercentage: (v) => v.passPercentage,
})
export async function middleware(request) {
const { pathname } = request.nextUrl
const result = await resolveAbRewrite(request, pathname, pathname, pathname)
return result ?? NextResponse.next()
}
export const config = { matcher: ['/((?!_next|api|favicon.ico).*)'] }
If the site has routes that must never be a variant (a preview or exit-preview route), pass
`reservedPathPrefixes` with those routes added to the defaults '/api', '/admin', '/_next'.
## Step 6: verify, and show me the output
With the app running, send each request and show me the status code.
Every one of them must be refused. If one succeeds, the policy is wrong: stop and tell me.
1. Anonymous variant creation, expect 401:
curl -i -X POST http://localhost:3000/api/ab/variants -H 'Content-Type: application/json' -d '{"collection":"pages","id":"<page id>"}'
2. The same request with the session cookie of a user whose role may not create variants, expect 403.
3. Anonymous manifest write, expect 403:
curl -i -X POST http://localhost:3000/api/globals/_abManifest -H 'Content-Type: application/json' -d '{"manifest":{}}'
4. The same manifest write with an admin's session cookie, expect 403.
5. Anonymous write to the experiments collection, expect 403:
curl -i -X POST http://localhost:3000/api/ab-experiments -H 'Content-Type: application/json' -d '{}'
6. As a user without splitTraffic, PATCH /api/pages/<variant id> with {"_abPassPercentage": 50}, expect 403.
Then, as a user with createVariant, press "Create variant" on a page and check that the copy appears.
Variants live inside the same collection as the original page:
pages collection
├── original slug: "about" _abVariantOf: null
├── variant A slug: "about--4ji9a2" _abVariantOf: <original id>
└── variant B slug: "about--x2k1f0" _abVariantOf: <original id>
On every save or delete, hooks rebuild the variant manifest, a plain JSON object keyed by URL path, and write it to the storage adapter. Next.js middleware reads the manifest at the edge to rewrite the request before any rendering happens.
Payload Admin → afterChange / afterDelete hooks → Storage Adapter
↓
{ "/about": [variantA, variantB] }
↓
Next.js Middleware (edge)
↓
Route user to original or variant
pnpm add @focus-reactive/payload-plugin-ab @focus-reactive/payload-plugin-guard
For the Vercel Edge adapter, also install:
pnpm add @vercel/edge-config
Peer dependencies: payload ^3.90.0 and @payloadcms/ui ^3.90.0.
next ^14 || ^15 || ^16 and react ^18 || ^19 are optional, required only for middleware and analytics respectively.
The plugin reads every right from your project's access policy file; see the guard README for the whole file. Add the entries for the collection and global the plugin owns, and a gate for each capability:
// src/access.policy.ts
import {
anyone,
defineAccessPolicy,
gate,
nobody,
panelUser,
} from "@focus-reactive/payload-plugin-guard";
import type { PayloadRequest } from "payload";
const rolesOf = (req: PayloadRequest): string[] =>
req.user?.collection === "users" ? (req.user.roles ?? []) : [];
const isAdmin = gate(({ req }) => rolesOf(req).includes("admin"));
const isMarketer = gate(({ req }) =>
rolesOf(req).some((role) => ["admin", "marketer"].includes(role))
);
export const accessPolicy = defineAccessPolicy({
collections: {
// ...your collections
"ab-experiments": { create: nobody, read: panelUser, update: nobody, delete: nobody },
},
globals: {
// ...your globals
_abManifest: { read: anyone, update: nobody },
},
jobs: { run: isAdmin, queue: isAdmin, cancel: isAdmin },
plugins: {
ab: { createVariant: isMarketer, splitTraffic: isAdmin },
},
});
create, update and delete of ab-experiments, and update of _abManifest, must be nobody; the boot fails otherwise.
// payload.config.ts
import { buildConfig } from "payload";
import { withAccessPolicy } from "@focus-reactive/payload-plugin-guard";
import { abTestingPlugin } from "@focus-reactive/payload-plugin-ab";
import { payloadGlobalAdapter } from "@focus-reactive/payload-plugin-ab/adapters/payload-global";
import { accessPolicy } from "./access.policy";
const abAdapter = payloadGlobalAdapter({
serverURL: process.env.NEXT_PUBLIC_SERVER_URL ?? "",
});
export default withAccessPolicy(
accessPolicy,
buildConfig({
plugins: [
abTestingPlugin({
storage: abAdapter,
access: accessPolicy.plugins.ab,
collections: {
pages: {
generatePath: ({ doc, locale }) => {
const slug = doc.slug as string | undefined;
if (!slug) return null;
return locale ? `/${locale}/${slug}` : `/${slug}`;
},
},
},
}),
],
})
);
access is required and has no default.
The plugin refuses to start without it, and withAccessPolicy checks that it got exactly the gates in accessPolicy.plugins.ab.
The plugin injects into every configured collection:
_abVariantOf and _abPassPercentage fields (hidden from editors)admin.baseListFilter to hide variant documents from the list viewbeforeChange, afterChange, beforeDelete and afterDelete hooksUpload and auth collections cannot have variants; the plugin refuses to start with one configured.
// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { createResolveAbRewrite } from "@focus-reactive/payload-plugin-ab/middleware";
import { payloadGlobalAdapter } from "@focus-reactive/payload-plugin-ab/adapters/payload-global";
const storage = payloadGlobalAdapter({
serverURL: process.env.NEXT_PUBLIC_SERVER_URL ?? "",
});
const resolveAbRewrite = createResolveAbRewrite({
storage,
getBucket: (v) => v.bucket,
getRewritePath: (v) => v.rewritePath,
getPassPercentage: (v) => v.passPercentage,
});
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
const result = await resolveAbRewrite(request, pathname, pathname, pathname);
return result ?? NextResponse.next();
}
export const config = {
matcher: ["/((?!_next|api|favicon.ico).*)"],
};
| Capability | Lets a user | Also needs, on the original page |
|---|---|---|
createVariant | create a variant with the Variants panel or POST /api/ab/variants, or link a document to an original page | read, create in the collection, update |
splitTraffic | change a variant's share of traffic, in the panel or by writing _abPassPercentage | update |
The capability says who may act at all. The document rights come from the policy entries you already wrote for the collection.
The A/B test panel in the sidebar of the original page shows only what the user can do:
Create variant and Add variant need createVariant, update rights on the page and create rights in the collection.
The traffic split can be changed only with splitTraffic and update rights on the page; everyone else sees the shares as read-only text, so their saves never carry a split the server would refuse.
Stop test and Delete variant need delete rights in the collection.
A user who can create no variant sees no panel on a page without a test.
Payload's Duplicate on a variant gives a standalone page outside the test, so it needs no capability and leaves the split as it was; a new variant comes only from Add variant.
POST /api/ab/variants takes { "collection": "<slug>", "id": "<id>" }.
The collection must be one of the configured collections, and the slug field comes from slugField in the config.
The copy is made with the caller's own rights and mirrors the original's status: a draft original gives a draft variant.
Anonymous callers get 401; users of another auth collection and users without the capability get 403.
A write that sets or changes _abVariantOf, or changes a variant's _abPassPercentage or tenant, is checked on the server for every caller, over REST, GraphQL and the Local API with overrideAccess: false.
The caller needs the capability and update rights on the original page, and on the old original too when a variant moves.
A variant cannot have variants, and with tenantField it must have its original's tenant.
_abPendingPercentages, the split staged on the original page, needs splitTraffic and takes whole percentages from 1 to 99.
Errors from the endpoint carry a generic message; details go to the server log.
Refusals (401 and 403) from the endpoint and from the plugin's hooks are logged at warn with the capability and the caller's kind.
GET /api/ab/capabilities answers a logged-in admin user with { "createVariant": boolean, "splitTraffic": boolean } for that user, so custom admin UI can hide controls; the server still checks every write.
| Slug | Kind | Written by | Read by |
|---|---|---|---|
ab-experiments | collection | the plugin only | your policy's read |
_abManifest | global, with the payload-global adapter | the plugin only | your policy's read, which must be anyone |
The manifest global must stay readable by anyone, because the site middleware reads it without a session.
For each original page with published variants, it holds the path of the page and the variants' buckets (their slugs), rewrite paths and shares of traffic.
These are published pages that visitors can already reach, so the manifest discloses nothing more, as long as a custom generateVariantData returns only routing data.
Whatever generateVariantData returns is public.
Each variant owns its own _abPassPercentage, versioned together with the variant document.
The draft version holds the value you are editing; the published version holds the value the manifest serves.
The original page has no stored copy of it.
Editing percentages in the Variants panel stages them in _abPendingPercentages, a virtual field with no database column, sent with the original's own save:
Each share is a whole number from 1 to 99, and the variants of one page take 99% or less, leaving the original at least 1%. Two saves that change shares of the same page at the same moment can each pass this check and together exceed 99%. The manifest is rebuilt from what is stored after every save; when the published shares exceed 99%, the plugin leaves that page out of the manifest and logs an error, so every visitor sees the original until the split is fixed.
// abTestingPlugin<TVariantData>(options) ties the storage adapter and generateVariantData to one variant type.
interface AbTestingPluginConfig<TVariantData extends object = object> {
storage: StorageAdapter<TVariantData>;
collections: Record<string, CollectionABConfig<TVariantData>>;
access: { createVariant: Gate; splitTraffic: Gate }; // required: accessPolicy.plugins.ab
enabled?: boolean; // default: true; when false, only the plugin's own collection and global are registered
debug?: boolean; // show the experiments collection in the admin. default: false
experimentsCollectionSlug?: string; // default: 'ab-experiments'
}
interface CollectionABConfig<TVariantData = DefaultVariantData> {
/**
* Name of the top-level field that holds the slug. Variant slugs are `{original}--{random}`.
* Default: 'slug'
*/
slugField?: string;
/**
* Dot-notation path to the tenant field.
* A variant always has its original's tenant; a write that would change that is refused.
*/
tenantField?: string;
/**
* Returns the URL path used as the manifest key; it must start with '/'.
* Return null to skip this document.
* Receives documents at depth 0, once per locale when localization is enabled.
*
* Must also return a valid path for variant slugs (e.g. 'about--4ji9a2')
* since it is used to compute rewritePath when generateVariantData is omitted.
*/
generatePath: (args: { doc: Record<string, unknown>; locale: string | undefined }) => string | null;
/**
* Builds the data stored per variant in the manifest, which anyone can read.
* When omitted, auto-generates: { bucket: variantSlug, rewritePath, passPercentage }
*/
generateVariantData?: (args: {
doc: Record<string, unknown>; // original document, depth 0
variantDoc: Record<string, unknown>; // variant document, depth 0
locale: string | undefined;
}) => TVariantData;
}
// Default shape when generateVariantData is omitted:
type DefaultVariantData = {
bucket: string; // variant's slug, e.g. 'about--4ji9a2'
rewritePath: string; // result of generatePath(variantDoc, locale)
passPercentage: number; // _abPassPercentage field value
};
type StorageAdapter<TVariantData extends object> =
// The manifest lives in a Payload global that the plugin creates, owns and writes.
| { globalSlug: string; read(path: string): Promise<TVariantData[] | null> }
// The manifest lives outside Payload; the plugin calls write and clear on the server.
| {
read(path: string): Promise<TVariantData[] | null>; // must be edge-compatible
write(path: string, variants: TVariantData[]): Promise<void>;
clear(path: string): Promise<void>;
};
Implement the second shape to use any backend (Redis, Upstash, Vercel KV, etc.). Manifest writes from one server process run one at a time. Writes from several server processes at the same moment can still overwrite each other's keys; the next save of an affected page writes its entry again.
Stores the manifest in a Payload global as a JSON field. Middleware fetches it through the Payload REST API.
import { payloadGlobalAdapter } from "@focus-reactive/payload-plugin-ab/adapters/payload-global";
const storage = payloadGlobalAdapter({
serverURL: "https://cms.example.com", // required for middleware reads
globalSlug: "_abManifest", // default
apiRoute: "/api", // default
});
The plugin creates and owns the global, and your policy needs an entry for it (see Access and capabilities).
It is never shown in the admin: it is a copy of the running experiments that only the plugin writes, for the middleware to read.
To inspect it, read GET /api/globals/_abManifest, or set debug: true to see the experiments collection it is built from.
Stores the manifest in Vercel Edge Config for sub-millisecond reads at the edge.
import { vercelEdgeAdapter } from "@focus-reactive/payload-plugin-ab/adapters/vercel-edge";
const storage = vercelEdgeAdapter({
configID: process.env.EDGE_CONFIG_ID!,
configURL: process.env.EDGE_CONFIG!,
vercelRestAPIAccessToken: process.env.VERCEL_REST_API_ACCESS_TOKEN!,
teamID: process.env.VERCEL_TEAM_ID, // optional
manifestKey: "ab-testing", // default
});
Required env vars: EDGE_CONFIG, EDGE_CONFIG_ID, VERCEL_REST_API_ACCESS_TOKEN.
Create an Edge Config store in the Vercel dashboard and install @vercel/edge-config.
A failed Edge Config update fails the save that caused it.
import { createResolveAbRewrite } from "@focus-reactive/payload-plugin-ab/middleware";
const resolveAbRewrite = createResolveAbRewrite({
storage, // same adapter as the plugin
getBucket: (v) => v.bucket, // extract bucket key
getRewritePath: (v) => v.rewritePath, // extract internal rewrite URL
getPassPercentage: (v) => v.passPercentage, // enables weighted routing
reservedPathPrefixes: ["/api", "/admin", "/_next"], // default
});
// In middleware:
const result = await resolveAbRewrite(
request,
pathname, // visiblePathname: used as the per-path cookie key
pathname, // manifestKey: key to look up in the manifest
pathname // originalRewritePath: where to send 'original' bucket users
);
The three path arguments let you decouple what the user sees, the manifest key, and the internal rewrite target, which is useful with locale prefixes:
const internalPath = `/${locale}${pathname}`;
await resolveAbRewrite(request, pathname, internalPath, internalPath);
Routing: when getPassPercentage is provided, each variant receives its percentage of traffic and the remainder goes to the original.
When it is omitted, all variants and the original share equal probability.
What the middleware accepts from the manifest: it treats the manifest as data from storage and keeps only sound variants.
/, no scheme or host, no //, no backslash, no . or .. segment, no encoded /, \ or ., no query or fragment./api, /admin and /_next.
Pass reservedPathPrefixes to add routes of your own that must never be a variant, such as a preview route, and keep the defaults in the list.original.
Unknown fields are ignored, and the manifest is looked up by its own keys only.Sticky assignment: bucket assignment is stored in a per-path cookie that outlives the browser session, so returning users always see the same variant. If the bucket cookie is gone, the middleware restores the assignment from the experiment cookie; a bucket whose variant no longer exists is drawn again.
| Cookie | Default name | Lifetime | Purpose |
|---|---|---|---|
| Bucket | payload_ab_bucket_{path} | 90 days | Which bucket this user is in |
| Visitor ID | ab_visitor_id | 365 days | Persistent visitor identifier for analytics |
| Experiment | exp_{path} | 90 days | Bucket name readable client-side by analytics hooks |
Override names and lifetimes (visitorIdMaxAge, expCookieMaxAge, bucketCookieMaxAge, in seconds) by passing a cookies config to createResolveAbRewrite:
import type { AbCookieConfig } from "@focus-reactive/payload-plugin-ab/middleware";
// Define once, share between middleware and analytics
export const abCookies: AbCookieConfig = {
visitorIdCookieName: "my_visitor_id",
getExpCookieName: (key) => `ab_exp_${key}`,
};
Use resolveAbCookieNames(config, experimentId) in Server Components to derive cookie names as plain strings for passing to Client Components:
import { resolveAbCookieNames } from "@focus-reactive/payload-plugin-ab/middleware";
const { variantCookieName, visitorCookieName } = resolveAbCookieNames(abCookies, "/en/about");
Mount <ExperimentTracker experimentId={manifestKey} /> on each variant-served page.
It stamps three GA4 event-scoped custom dimensions on every subsequent event:
fr_ab_experiment: the experiment id (manifest key, e.g. /en/about)fr_ab_variant: the assigned bucket (original or a variant slug)fr_ab_visitor_id: the ab_visitor_id cookie valueRegister these three dimensions in your GA4 property.
The @focus-reactive/payload-plugin-analytics A/B tab reads them to compute exposure, conversion-rate, lift, significance, and SRM.
Conversions are the analytics plugin's existing lead_action events on the experiment page; there is no separate AB conversion event.
The plugin creates and owns an ab-experiments collection (hidden unless debug: true).
It records each experiment's startedAt when the first variant is published.
Only the plugin writes it; your policy decides who reads it.
// app/[locale]/[slug]/page.tsx (Server Component)
import { ExperimentTracker } from "@focus-reactive/payload-plugin-ab/analytics/client";
import { resolveAbCookieNames } from "@focus-reactive/payload-plugin-ab/middleware";
export default async function Page({ params }) {
const experimentId = `/${params.locale}/${params.slug}`;
const { variantCookieName, visitorCookieName } = resolveAbCookieNames(undefined, experimentId);
return (
<>
{/* page content */}
<ExperimentTracker
experimentId={experimentId}
variantCookieName={variantCookieName}
visitorCookieName={visitorCookieName}
/>
</>
);
}
ExperimentTracker is a Client Component. Props:
| Prop | Type | Required | Description |
|---|---|---|---|
experimentId | string | Yes | Manifest key (URL path, e.g. /en/about) |
variantCookieName | string | No | Override the cookie name for variant bucket (use resolveAbCookieNames) |
visitorCookieName | string | No | Override the cookie name for visitor ID (use resolveAbCookieNames) |
abTestingPlugin({
storage,
access: accessPolicy.plugins.ab,
collections: {
pages: {
tenantField: "tenant", // dot-notation path to the tenant field
generatePath: ...,
},
},
});
When set, the server keeps every variant in its original's tenant:
Who may read and write each tenant's pages is decided by your policy entries for the collection, which every variant write goes through. Percentage validation is per original page, so it never mixes tenants.
No extra config needed.
When payload.config.localization is set, the plugin iterates every locale on each save and writes a separate manifest entry per locale.
locale is undefined when localization is not configured.
generatePath: ({ doc, locale }) => {
const slug = doc.slug as string | undefined;
if (!slug) return null;
return locale ? `/${locale}/${slug}` : `/${slug}`; // '/en/about', '/fr/about'
};
3.0 moves the plugin onto @focus-reactive/payload-plugin-guard; Upgrading to the guard explains the model all the plugins share, with a complete example.
Every access rule is now written by hand in your project's src/access.policy.ts, and nothing is open by default: an entry you leave out stops the boot, and a capability you do not grant is refused for everyone.
@payloadcms/* package 3.90 or later, with the React and Next versions Payload 3.90 requires, Node 22.22 or later, and @focus-reactive/payload-plugin-guard installed next to the plugin.access is a required option with no default; the plugin's two capabilities replace the old open endpoint.POST /api/_ab/duplicate with { collectionSlug, docId, slugField } to POST /api/ab/variants with { collection, id }.
The slug field comes from slugField in the plugin config, and the Variants panel already uses the new endpoint._abVariantOf, or changing a variant's _abPassPercentage, is checked on the server for every caller, over REST, GraphQL and the Local API with overrideAccess: false: it needs the capability and update rights on the original page.ab-experiments and _abManifest are refused for everyone, and who reads ab-experiments is decided by your policy; it is no longer readable by anyone by default.write(path, variants) and clear(path) no longer receive payload, and createGlobal is gone.
An adapter that keeps the manifest in a Payload global returns { globalSlug, read }, and the plugin creates and writes that global; code that read abAdapter.createGlobal(false).slug reads abAdapter.globalSlug.generatePath and generateVariantData receive documents at depth 0, not 1./api, /admin and /_next, and shares that are not whole numbers from 1 to 99; a variant at 100% is no longer served.slugField must be a top-level field of the collection.abTestingPlugin<MyVariantData>({ ... }) types storage and generateVariantData together, as before.Upgrade payload and every @payloadcms/* package to 3.90 or later, run the server on Node 22.22 or later, and install the guard:
pnpm add @focus-reactive/payload-plugin-guard @focus-reactive/payload-plugin-ab.
Add the plugin's entries to src/access.policy.ts, with gates for your own roles; if the project has no policy file yet, write it first as the guide describes.
// src/access.policy.ts, inside defineAccessPolicy({ ... })
collections: {
"ab-experiments": { create: nobody, read: panelUser, update: nobody, delete: nobody },
},
globals: {
_abManifest: { read: anyone, update: nobody },
},
plugins: {
ab: { createVariant: isMarketer, splitTraffic: isAdmin },
},
createVariant: copy a page as a variant, or link a document to an original page; the user also needs read and create rights in the collection and update rights on the original.splitTraffic: change a variant's share of traffic; the user also needs update rights on the original.ab-experiments: the experiment records, written only by the plugin; read decides who sees them, also in the analytics A/B tab._abManifest (with the payload-global adapter): the routing manifest, written only by the plugin; read must be anyone, because the site middleware reads it without a session.Pass access: accessPolicy.plugins.ab to abTestingPlugin, and export the config wrapped: export default withAccessPolicy(accessPolicy, buildConfig({ ... })).
Database: no migration; the plugin's collection, global and fields keep their columns.
Re-test: an anonymous POST /api/ab/variants answers 401 and one from a user without createVariant 403; a REST write to /api/globals/_abManifest as an admin answers 403; a user with createVariant creates a variant from the Variants panel; a user with splitTraffic publishes a new split, and the middleware serves the variant at its share.
| Import path | Exports |
|---|---|
@focus-reactive/payload-plugin-ab | abTestingPlugin, AbTestingPluginConfig, CollectionABConfig, StorageAdapter, AbCookieConfig, resolveAbCookieNames, ResolvedAbCookieNames, AB_EXPERIMENTS_SLUG, AB_DIMENSION_PARAMS |
@focus-reactive/payload-plugin-ab/adapters/payload-global | payloadGlobalAdapter |
@focus-reactive/payload-plugin-ab/adapters/vercel-edge | vercelEdgeAdapter |
@focus-reactive/payload-plugin-ab/middleware | createResolveAbRewrite, resolveAbCookieNames, AbCookieConfig, ResolveAbRewriteConfig |
@focus-reactive/payload-plugin-ab/analytics | ExperimentTracker, ExperimentTrackerProps, AbCookieConfig, resolveAbCookieNames, ResolvedAbCookieNames |
@focus-reactive/payload-plugin-ab/analytics/client | ExperimentTracker, ExperimentTrackerProps, AbCookieConfig, resolveAbCookieNames, ResolvedAbCookieNames |
Topics
Tags
payload plugin analytics
GA4-backed analytics dashboard in the Payload admin with a client-side tracking layer for Next.js front ends
70821/wk37v3
payload plugin presets
Save and apply reusable block configurations as presets from the Payload admin blocks drawer
786.7k/wk37v3
payload plugin comments
Document-level and field-level comments with mentions, resolution and email notifications for Payload admin
757.0k/wk37v3
payload plugin html preview
Live preview and click-to-edit in the Payload admin for any frontend that renders HTML, no framework needed
74451/wk37v3
payload plugin guard
Central access policy file, typed predicates and guarded endpoints for Payload plugins and Local API calls
73664/wk37v3
payload plugin netlify deploy
Deploy button in the Payload admin that builds a Netlify site, streams the log, and publishes a preview
72370/wk37v3