focusreactive

payload plugin ab

by focusreactive
payload-plugins
Analytics
v3
^3.90.0
MIT

Overview

Summary generated from the README

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.

Features

  • Variants panel on original pages to add variants and set traffic percentages
  • Variants kept in the same collection and hidden from the list view
  • Manifest stored in a Payload global or in Vercel Edge Config
  • Next.js middleware helper with weighted routing and per-path cookies
  • Capabilities for creating variants and splitting traffic, enforced in the access policy
  • Staged percentages applied on draft save or publish of the original

Use cases

  • Test alternative landing page versions and split traffic between them
  • Let marketers create page variants without developer involvement
  • Route visitors to variants at the edge without rendering delays

From the author

A/B testing plugin for Payload CMS

Installation

npm i @focus-reactive/payload-plugin-ab

37

Stars

5

Forks

33

Open Issues

Today

Last Updated

652

Weekly Downloads

v3.0.1

npm Version

261.6 KB

Unpacked Size

1

Dependencies

Repository stars

37+22 since Sep 7

Show data
Repository stars by day (UTC)
DateStars
Dec 6, 202637
Dec 5, 202637
Dec 4, 202637
Dec 3, 202637
Dec 2, 202637
Dec 1, 202636
Nov 30, 202635
Nov 29, 202635
Nov 28, 202634
Nov 27, 202634
Nov 26, 202634
Nov 25, 202634
Nov 24, 202634
Nov 23, 202634
Nov 22, 202634
Nov 21, 202634
Nov 20, 202633
Nov 19, 202632
Nov 18, 202632
Nov 17, 202632
Nov 16, 202632
Nov 15, 202632
Nov 14, 202632
Nov 13, 202632
Nov 12, 202632
Nov 11, 202632
Nov 10, 202632
Nov 9, 202631
Nov 8, 202631
Nov 7, 202631
Nov 6, 202631
Nov 5, 202631
Nov 4, 202630
Nov 3, 202630
Nov 2, 202630
Nov 1, 202630
Oct 31, 202630
Oct 30, 202630
Oct 29, 202630
Oct 28, 202630
Oct 27, 202630
Oct 26, 202630
Oct 25, 202630
Oct 24, 202629
Oct 23, 202629
Oct 22, 202629
Oct 21, 202629
Oct 20, 202629
Oct 19, 202629
Oct 18, 202629
Oct 17, 202627
Oct 16, 202626
Oct 15, 202626
Oct 14, 202626
Oct 13, 202625
Oct 12, 202625
Oct 11, 202625
Oct 10, 202625
Oct 9, 202625
Oct 8, 202625
Oct 7, 202625
Oct 6, 202624
Oct 5, 202624
Oct 4, 202624
Oct 3, 202623
Oct 2, 202622
Oct 1, 202622
Sep 30, 202620
Sep 29, 202620
Sep 28, 202620
Sep 27, 202620
Sep 26, 202619
Sep 25, 202618
Sep 24, 202618
Sep 23, 202618
Sep 22, 202618
Sep 21, 202618
Sep 20, 202618
Sep 19, 202618
Sep 18, 202618
Sep 17, 202618
Sep 16, 202618
Sep 15, 202618
Sep 14, 202618
Sep 13, 202617
Sep 12, 202617
Sep 11, 202617
Sep 10, 202616
Sep 9, 202616
Sep 8, 202616
Sep 7, 202615

Shared by 15 plugins in focusreactive/payload-plugins.

npm weekly downloads

652+529 since Sep 7

Show data
npm weekly downloads by day (UTC)
DateWeekly downloads
Dec 6, 2026652
Dec 5, 2026658
Dec 4, 2026664
Dec 3, 2026682
Dec 2, 2026642
Dec 1, 2026616
Nov 30, 2026587
Nov 29, 2026412
Nov 28, 2026358
Nov 27, 2026345
Nov 26, 2026510
Nov 25, 2026512
Nov 24, 2026535
Nov 23, 2026578
Nov 22, 2026556
Nov 21, 2026578
Nov 20, 2026614
Nov 19, 2026445
Nov 18, 2026568
Nov 17, 2026552
Nov 16, 2026508
Nov 15, 2026605
Nov 14, 2026693
Nov 13, 2026641
Nov 12, 2026643
Nov 11, 2026689
Nov 10, 2026732
Nov 9, 2026843
Nov 8, 2026803
Nov 7, 2026715
Nov 6, 2026723
Nov 5, 2026734
Nov 4, 2026539
Nov 3, 2026504
Nov 2, 2026546
Nov 1, 2026547
Oct 31, 2026533
Oct 30, 2026535
Oct 29, 2026419
Oct 28, 2026388
Oct 27, 2026407
Oct 26, 2026276
Oct 25, 2026245
Oct 24, 2026261
Oct 23, 2026186
Oct 22, 2026235
Oct 21, 2026254
Oct 20, 2026223
Oct 19, 2026204
Oct 18, 2026221
Oct 17, 2026187
Oct 16, 2026273
Oct 15, 2026424
Oct 14, 2026522
Oct 13, 2026526
Oct 12, 2026518
Oct 11, 2026514
Oct 10, 2026538
Oct 9, 2026474
Oct 8, 2026331
Oct 7, 2026295
Oct 6, 2026314
Oct 5, 2026635
Oct 4, 2026647
Oct 3, 2026706
Oct 2, 2026707
Oct 1, 2026733
Sep 30, 2026714
Sep 29, 2026708
Sep 28, 2026393
Sep 27, 2026347
Sep 26, 2026264
Sep 25, 2026263
Sep 24, 2026190
Sep 23, 2026151
Sep 22, 2026137
Sep 21, 2026165
Sep 20, 2026159
Sep 19, 2026240
Sep 18, 2026252
Sep 17, 2026341
Sep 16, 2026364
Sep 15, 2026383
Sep 14, 2026348
Sep 13, 2026351
Sep 12, 2026256
Sep 11, 2026250
Sep 10, 2026170
Sep 9, 2026147
Sep 8, 2026122
Sep 7, 2026123

Each point is npm's rolling 7-day download count.

Health Score

73/100Good

Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.

Badge for your README

Payload Directory health badge
Markdown
[![Payload Directory](https://payloaddirectory.dev/badge/1177993877-payload-plugin-ab.svg)](https://payloaddirectory.dev/plugins/1177993877-payload-plugin-ab)
HTML
<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>
Updated Dec 5, 2026Created Mar 10, 2026Published Dec 4, 2026

README

@focus-reactive/payload-plugin-ab

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.


AI Integration Prompt

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.

How It Works

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

Installation

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.


Quick Start

Step 1: Grant the plugin's capabilities in your access policy

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.

Step 2: 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({
    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:

  • Variants panel (sidebar on original pages): lists variants with % inputs, add, delete
  • "Variant of" relationship (sidebar on variant pages)
  • _abVariantOf and _abPassPercentage fields (hidden from editors)
  • admin.baseListFilter to hide variant documents from the list view
  • beforeChange, afterChange, beforeDelete and afterDelete hooks

Upload and auth collections cannot have variants; the plugin refuses to start with one configured.

Step 3: Wire up middleware

// 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).*)"],
};

Access and capabilities

CapabilityLets a userAlso needs, on the original page
createVariantcreate a variant with the Variants panel or POST /api/ab/variants, or link a document to an original pageread, create in the collection, update
splitTrafficchange a variant's share of traffic, in the panel or by writing _abPassPercentageupdate

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.

What the plugin owns

SlugKindWritten byRead by
ab-experimentscollectionthe plugin onlyyour policy's read
_abManifestglobal, with the payload-global adapterthe plugin onlyyour 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.


Traffic percentages

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:

  • Save draft on the original writes the new percentages to each variant's draft. Live traffic keeps using the previously published split.
  • Publish on the original applies them to the published variants. Only the percentage is published: a variant's unpublished content stays unpublished, and goes live when you publish that variant itself.
  • A variant that has never been published takes no traffic, whatever its percentage says.

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.


When the original page changes

  • Publish or save: the page's manifest entries are rebuilt from its published variants, in every locale.
  • Path change: the entry under the old path is removed.
  • Unpublish: the page's manifest entries are removed and its published variants are unpublished, so no variant stays live without its original.
  • Delete: its variants are deleted, and its manifest entries and experiment records are removed.
  • A variant moves to another original page: the entries of both pages are rebuilt.

Configuration Reference

Plugin Options

// 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'
}

CollectionABConfig

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
};

StorageAdapter

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.


Storage Adapters

payloadGlobalAdapter

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.

vercelEdgeAdapter

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.


Middleware

createResolveAbRewrite

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.

  • A rewrite path must be a same-origin path: one leading /, no scheme or host, no //, no backslash, no . or .. segment, no encoded /, \ or ., no query or fragment.
  • A rewrite path under a reserved prefix is ignored. The defaults are /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.
  • A share must be a whole number from 1 to 99, and a variant with any other value is ignored. When the shares add up to more than 99, the page is served without the experiment.
  • Buckets must be non-empty strings, unique, and not 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.

CookieDefault nameLifetimePurpose
Bucketpayload_ab_bucket_{path}90 daysWhich bucket this user is in
Visitor IDab_visitor_id365 daysPersistent visitor identifier for analytics
Experimentexp_{path}90 daysBucket 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");

Analytics integration

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 value

Register 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.

Using ExperimentTracker

// 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:

PropTypeRequiredDescription
experimentIdstringYesManifest key (URL path, e.g. /en/about)
variantCookieNamestringNoOverride the cookie name for variant bucket (use resolveAbCookieNames)
visitorCookieNamestringNoOverride the cookie name for visitor ID (use resolveAbCookieNames)

Multi-Tenant Support

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:

  • A variant created with the endpoint is a copy and keeps the original's tenant.
  • A write that links a document to an original page of another tenant, or changes a variant's tenant, is refused with a validation error.
  • The tenant field is hidden on variant pages in the admin.

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.


Localization Support

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'
};

Migrating from 2.x

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.

What changes

  • Payload and every @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.
  • The variant endpoint moved from 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.
  • Setting or changing _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.
  • REST and GraphQL writes to 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.
  • Custom storage adapters: 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.
  • The middleware ignores rewrite paths under /api, /admin and /_next, and shares that are not whole numbers from 1 to 99; a variant at 100% is no longer served.
  • Unpublishing an original page unpublishes its variants, and deleting it deletes them, instead of leaving them as standalone published pages.
  • Upload and auth collections can no longer be configured, and slugField must be a top-level field of the collection.
  • The type argument stays: abTestingPlugin<MyVariantData>({ ... }) types storage and generateVariantData together, as before.

Steps

  1. 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.

  2. 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.
  3. Pass access: accessPolicy.plugins.ab to abTestingPlugin, and export the config wrapped: export default withAccessPolicy(accessPolicy, buildConfig({ ... })).

  4. Database: no migration; the plugin's collection, global and fields keep their columns.

  5. 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.


Exports Reference

Import pathExports
@focus-reactive/payload-plugin-ababTestingPlugin, AbTestingPluginConfig, CollectionABConfig, StorageAdapter, AbCookieConfig, resolveAbCookieNames, ResolvedAbCookieNames, AB_EXPERIMENTS_SLUG, AB_DIMENSION_PARAMS
@focus-reactive/payload-plugin-ab/adapters/payload-globalpayloadGlobalAdapter
@focus-reactive/payload-plugin-ab/adapters/vercel-edgevercelEdgeAdapter
@focus-reactive/payload-plugin-ab/middlewarecreateResolveAbRewrite, resolveAbCookieNames, AbCookieConfig, ResolveAbRewriteConfig
@focus-reactive/payload-plugin-ab/analyticsExperimentTracker, ExperimentTrackerProps, AbCookieConfig, resolveAbCookieNames, ResolvedAbCookieNames
@focus-reactive/payload-plugin-ab/analytics/clientExperimentTracker, ExperimentTrackerProps, AbCookieConfig, resolveAbCookieNames, ResolvedAbCookieNames

Similar plugins