xtr-dev

payload feature flags

by xtr-dev
Other
v3
^3.56.0

Overview

Summary generated from the README

Adds a feature-flags collection to Payload with on/off state, percentage rollouts and weighted variants. Flags are read through server helpers for React Server Components, client hooks, or an optional public evaluate endpoint. Bucketing is deterministic per flag and user. Requires Payload 3.56 or later and React 19.

Features

  • Feature-flags collection with enabled state, rollout percentage, weighted variants, tags and metadata
  • Server helpers for React Server Components wrapped in React cache
  • Client hooks and a higher-order component for flag, variant and rollout checks
  • Optional public evaluate endpoint so collection read access can stay closed
  • Admin dashboard with search, sorting, totals and inline toggles
  • Optional cross-request cache cleared automatically when a flag changes

Use cases

  • Roll out a new feature gradually to a percentage of users
  • Run A/B tests with weighted variants assigned consistently per user
  • Toggle features on or off from the admin panel without redeploying

From the author

Feature flags plugin for Payload CMS - manage feature toggles, A/B tests, and gradual rollouts

Installation

npm i @xtr-dev/payload-feature-flags

4

Stars

0

Forks

0

Open Issues

1 weeks ago

Last Updated

508

Weekly Downloads

v0.3.0

npm Version

252.0 KB

Unpacked Size

0

Dependencies

GitHub stars

4+1 since Sep 6

Show data
GitHub stars by day (UTC)
DateStars
Dec 5, 20264
Dec 4, 20264
Dec 3, 20264
Dec 2, 20264
Dec 1, 20264
Nov 30, 20264
Nov 29, 20264
Nov 28, 20264
Nov 27, 20264
Nov 26, 20264
Nov 25, 20264
Nov 24, 20264
Nov 23, 20264
Nov 22, 20264
Nov 21, 20264
Nov 20, 20264
Nov 19, 20264
Nov 18, 20264
Nov 17, 20264
Nov 16, 20264
Nov 15, 20264
Nov 14, 20264
Nov 13, 20264
Nov 12, 20264
Nov 11, 20264
Nov 10, 20264
Nov 9, 20264
Nov 8, 20264
Nov 7, 20264
Nov 6, 20264
Nov 5, 20264
Nov 4, 20264
Nov 3, 20264
Nov 2, 20264
Nov 1, 20264
Oct 31, 20264
Oct 30, 20264
Oct 29, 20264
Oct 28, 20264
Oct 27, 20264
Oct 26, 20264
Oct 25, 20264
Oct 24, 20264
Oct 23, 20264
Oct 22, 20264
Oct 21, 20264
Oct 20, 20264
Oct 19, 20264
Oct 18, 20264
Oct 17, 20264
Oct 16, 20264
Oct 15, 20264
Oct 14, 20264
Oct 13, 20264
Oct 12, 20264
Oct 11, 20264
Oct 10, 20264
Oct 9, 20264
Oct 8, 20264
Oct 7, 20264
Oct 6, 20264
Oct 5, 20264
Oct 4, 20264
Oct 3, 20264
Oct 2, 20264
Oct 1, 20264
Sep 30, 20264
Sep 29, 20264
Sep 28, 20264
Sep 27, 20264
Sep 26, 20264
Sep 25, 20264
Sep 24, 20264
Sep 23, 20264
Sep 22, 20264
Sep 21, 20264
Sep 20, 20264
Sep 19, 20264
Sep 18, 20264
Sep 17, 20264
Sep 16, 20263
Sep 15, 20263
Sep 14, 20263
Sep 13, 20263
Sep 12, 20263
Sep 11, 20263
Sep 10, 20263
Sep 9, 20263
Sep 8, 20263
Sep 7, 20263
Sep 6, 20263
npm weekly downloads

671+647 since Sep 6

Show data
npm weekly downloads by day (UTC)
DateWeekly downloads
Dec 5, 2026671
Dec 4, 2026797
Dec 3, 2026796
Dec 2, 2026754
Dec 1, 2026785
Nov 30, 2026839
Nov 29, 2026630
Nov 28, 2026509
Nov 27, 2026331
Nov 26, 2026363
Nov 25, 2026395
Nov 24, 2026346
Nov 23, 2026268
Nov 22, 2026159
Nov 21, 2026108
Nov 20, 2026105
Nov 19, 2026100
Nov 18, 2026104
Nov 17, 2026128
Nov 16, 2026176
Nov 15, 2026179
Nov 14, 2026181
Nov 13, 2026232
Nov 12, 2026267
Nov 11, 2026269
Nov 10, 2026254
Nov 9, 2026205
Nov 8, 2026196
Nov 7, 2026202
Nov 6, 2026189
Nov 5, 2026123
Nov 4, 202684
Nov 3, 202666
Nov 2, 202666
Nov 1, 202668
Oct 31, 202652
Oct 30, 202616
Oct 29, 202615
Oct 28, 202612
Oct 27, 202615
Oct 26, 202627
Oct 25, 202654
Oct 24, 2026104
Oct 23, 2026101
Oct 22, 2026103
Oct 21, 2026123
Oct 20, 2026120
Oct 19, 2026108
Oct 18, 202677
Oct 17, 202625
Oct 16, 202626
Oct 15, 202685
Oct 14, 2026109
Oct 13, 2026142
Oct 12, 2026156
Oct 11, 2026169
Oct 10, 2026171
Oct 9, 2026173
Oct 8, 2026115
Oct 7, 202672
Oct 6, 202639
Oct 5, 202626
Oct 4, 202612
Oct 3, 202617
Oct 2, 202623
Oct 1, 202624
Sep 30, 202632
Sep 29, 202643
Sep 28, 202642
Sep 27, 202649
Sep 26, 202646
Sep 25, 202643
Sep 24, 202657
Sep 23, 202650
Sep 22, 202642
Sep 21, 202658
Sep 20, 202653
Sep 19, 202652
Sep 18, 202650
Sep 17, 202634
Sep 16, 202635
Sep 15, 202632
Sep 14, 202618
Sep 13, 202615
Sep 12, 202616
Sep 11, 202621
Sep 10, 202619
Sep 9, 202620
Sep 8, 202621
Sep 7, 202620
Sep 6, 202624

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/1055577181-root.svg)](https://payloaddirectory.dev/plugins/1055577181-root)
HTML
<a href="https://payloaddirectory.dev/plugins/1055577181-root"><img src="https://payloaddirectory.dev/badge/1055577181-root.svg" alt="Payload Directory"></a>
Updated Nov 28, 2026Created Sep 12, 2025Published Nov 27, 2026

README

@xtr-dev/payload-feature-flags

Feature flags plugin for Payload CMS v3. Manage feature toggles, A/B tests, and rollouts from your admin panel.

v0.x — minor versions may contain breaking changes until 1.0.

Features

  • A feature-flags collection with on/off state, percentage rollouts, weighted variants, tags and metadata
  • Helpers for React Server Components and React hooks for client components
  • Deterministic per-flag bucketing, identical on the server, in the public endpoint and in the client hooks
  • An admin dashboard at /admin/feature-flags-overview
  • Optional public evaluate endpoint, so the collection's read access can stay closed
  • Optional cross-request cache, cleared automatically when a flag changes

Requirements

  • payload and @payloadcms/ui ^3.56.0
  • react ^19.1.0
  • Node.js ^18.20.2 or >=20.9.0

Installation

pnpm add @xtr-dev/payload-feature-flags

Add the plugin to your Payload config:

import { buildConfig } from 'payload'
import { payloadFeatureFlags } from '@xtr-dev/payload-feature-flags'

export default buildConfig({
  // ...
  plugins: [payloadFeatureFlags()],
})

Then regenerate the admin import map, since the plugin adds admin components:

pnpm payload generate:importmap

Upgrading to 0.3.0

0.3.0 corrects the FeatureFlag type exported from the root entry point. It used to describe a stored document (id, createdAt, updatedAt), but declared an environment field the plugin never adds and left out the null Payload returns for empty optional fields. Only types change; nothing behaves differently at runtime.

  • FeatureFlag from @xtr-dev/payload-feature-flags is now the type the helpers and hooks return, the same one /rsc and /client already exported. It has no id, createdAt, updatedAt or environment.
  • If you used the root FeatureFlag for documents read with payload.find or the REST API, switch to the new FeatureFlagDocument, and handle null for description, rolloutPercentage, tags and variants (for example flag.rolloutPercentage ?? 100).
  • For fields you added through collectionOverrides.fields (such as environment), use the FeatureFlag type from your own generated payload-types.ts.

See Types.

Upgrading to 0.2.0

0.2.0 changes how users are bucketed (#54):

  • Rollouts and variants are bucketed per flag (a hash of the flag name and user ID). Existing users get new buckets and new variants, so running experiments restart with a fresh split. Finish an experiment, or roll its winner out to 100%, before upgrading if you need to keep assignments.
  • rolloutPercentage: 0 now means nobody. Before, it let everyone in. Set it to 100, or clear it, if you relied on that.
  • If you copied hashing code from an earlier README, switch to isUserInRolloutBucket / selectVariantForUser (see Bucketing).

The admin dashboard now points at the FeatureFlagsOverviewView export, so run payload generate:importmap after upgrading.

Options

All options are optional.

OptionDefaultDescription
disabledfalseSkip the /admin/feature-flags-overview view and the public endpoint. The collection is still added, so the database schema stays the same.
defaultValuefalseDefault of the enabled field for new flags.
enableRolloutstrueAdd the rolloutPercentage field.
enableVariantstrueAdd the variants field.
enableCustomListViewfalseReplace the collection's list view with the dashboard. Merges with collectionOverrides.admin.components.
publicEndpointfalseAdd GET /api/<collection>/evaluate. See Public endpoint.
cachefalseCache the RSC helpers across requests. See Caching.
collectionOverridesAny CollectionConfig property (slug, access, admin, hooks, versions, ...), plus fields: ({ defaultFields }) => Field[]. The slug defaults to feature-flags.
payloadFeatureFlags({
  collectionOverrides: {
    slug: 'my-feature-flags',
    access: {
      read: ({ req: { user } }) => !!user,
      update: ({ req: { user } }) => user?.role === 'admin',
    },
    fields: ({ defaultFields }) => [
      ...defaultFields,
      { name: 'expiresAt', type: 'date' },
    ],
  },
})

The plugin records the collection slug in config.custom.payloadFeatureFlags.collectionSlug, which is where the server helpers read it from.

Collection fields

  • name (text, required, unique): the flag's identifier
  • description (textarea)
  • enabled (checkbox, required)
  • rolloutPercentage (number 0-100, default 100): share of users who get the flag. Empty means everyone, 0 means nobody.
  • variants (array of name, weight, metadata): weights are percentages. When they add up to less than 100, users in the remaining buckets get the first variant.
  • tags (array of tag)
  • metadata (JSON)

rolloutPercentage and variants only show in the admin panel while the flag is enabled.

Server Components

import { getPayload } from 'payload'
import config from '@payload-config'
import { isFeatureEnabled, getUserVariant } from '@xtr-dev/payload-feature-flags/rsc'

export default async function ProductPage({ userId }: { userId: string }) {
  const payload = await getPayload({ config })

  if (!(await isFeatureEnabled('new-product-page', payload))) {
    return <LegacyProductPage />
  }

  const variant = await getUserVariant('product-layout-test', userId, payload)
  return variant === 'layout-b' ? <LayoutB /> : <LayoutA />
}

All helpers take the payload instance as their last argument, and are wrapped in React cache(), so repeated calls in one request read the database once.

FunctionReturns
getFeatureFlag(name, payload)The flag, or null
isFeatureEnabled(name, payload)boolean
getAllFeatureFlags(payload)Enabled flags keyed by name
isUserInRollout(name, userId, payload)boolean; false when the flag is disabled
getUserVariant(name, userId, payload)Variant name, or null when the flag is disabled or has no variants
getFeatureFlagsByTag(tag, payload)Flags with that tag

A flag here is a FeatureFlag: name, enabled, and optional description, rolloutPercentage, variants, tags and metadata. Lookups that fail log the error and return null, {} or [].

Client components

'use client'
import { useFeatureFlag, useVariantSelection } from '@xtr-dev/payload-feature-flags/client'

export function Banner({ userId }: { userId: string }) {
  const { isEnabled, loading } = useFeatureFlag('new-banner')
  const { variant } = useVariantSelection('banner-copy-test', userId)

  if (loading || !isEnabled) return null
  return <p>{variant === 'short' ? 'Hi!' : 'Welcome back, good to see you!'}</p>
}
HookReturns
useFeatureFlags(initialFlags, options?){ flags, loading, error, refetch } for the flags named in initialFlags, in the same order
useFeatureFlag(name, options?){ isEnabled, flag, loading, error }
useSpecificFeatureFlag(name, options?){ flag, loading, error, refetch }
useVariantSelection(name, userId, options?){ variant, flag, loading, error }
useRolloutCheck(name, userId, options?){ isInRollout, flag, loading, error }
withFeatureFlag(name, Fallback?, options?)(Component)A component that renders Component when the flag is on, else Fallback (or nothing)

options (FeatureFlagOptions): serverURL (defaults to the page's origin), apiPath (/api), collectionSlug (feature-flags), and source:

  • 'collection' (default): reads Payload's REST API for the collection, so visitors need read access. flag holds the whole flag, including description and tags.
  • 'public': reads the public endpoint. flag holds only name and enabled; variant and rollout are resolved on the server, and a missing flag shows as disabled instead of an error.

Types

The root entry point exports two types for a flag:

TypeWhat it describes
FeatureFlagWhat the server helpers and client hooks return: name, enabled, and optional description, rolloutPercentage, variants, tags and metadata. Empty optional fields are undefined, never null. Also exported from /rsc and /client.
FeatureFlagDocumentA document as Payload stores and returns it (payload.find, the REST API, collection hooks): the fields above plus id, createdAt and updatedAt. Empty optional fields are null, and array rows carry an id.
import type { FeatureFlag, FeatureFlagDocument } from '@xtr-dev/payload-feature-flags'

const flag: FeatureFlag | null = await getFeatureFlag('new-dashboard', payload)

const { docs } = await payload.find({ collection: 'feature-flags' })
const documents: FeatureFlagDocument[] = docs
const percentage = documents[0].rolloutPercentage ?? 100 // null means no gradual rollout

Neither type includes fields added through collectionOverrides.fields. For those, use the FeatureFlag type in your generated payload-types.ts, which is assignable to FeatureFlagDocument.

Public endpoint

To keep the collection's read access closed, turn on publicEndpoint and call the hooks with source: 'public':

payloadFeatureFlags({
  publicEndpoint: true,
  collectionOverrides: {
    access: { read: ({ req: { user } }) => !!user },
  },
})
const { isEnabled } = useFeatureFlag('new-homepage', { source: 'public' })
const { variant } = useVariantSelection('checkout-test', userId, { source: 'public' })

GET /api/<collection>/evaluate?names=a,b&userId=u returns { flags: { [name]: { name, enabled, variant?, inRollout? } } } (types PublicFeatureFlagsResponse and PublicFeatureFlag). It answers every name you pass (at most 100), and a name with no flag gets enabled: false, so the response does not reveal which flags exist. It never lists all flags. variant and inRollout are only included when userId is sent.

The endpoint is public by design: anyone can ask for the on/off state of a flag they can name, and for the variant and rollout result of any userId. Don't put secrets in flag names, and don't rely on users being unable to see other users' buckets.

Bucketing

isUserInRolloutBucket(flagName, userId, rolloutPercentage) and selectVariantForUser(flagName, userId, variants) are exported from the root and /client entry points. Use them to evaluate flags you fetched yourself, for example from the REST API, with the same result as the plugin:

import { isUserInRolloutBucket, selectVariantForUser } from '@xtr-dev/payload-feature-flags'

const { docs } = await fetch('/api/feature-flags?where[name][equals]=new-feature').then((r) => r.json())
const flag = docs[0]

const inRollout = flag?.enabled && isUserInRolloutBucket(flag.name, userId, flag.rolloutPercentage)
const variant = flag?.enabled ? selectVariantForUser(flag.name, userId, flag.variants) : null

Buckets come from a hash of the flag name and the user ID, so each flag splits users independently, and a flag's rollout and its variant assignment are independent of each other too.

Caching

The RSC helpers read the database on every request unless you turn on cache:

payloadFeatureFlags({
  cache: true, // Next.js unstable_cache, tag 'payload-feature-flags', revalidate 60s
  // or: cache: { tag: 'my-flags', revalidate: 300 },
})

The plugin appends afterChange and afterDelete hooks to the collection (after your own) that clear the cache, so a changed flag shows on the next request. This also works outside a request inside the Next.js process, such as Payload jobs, except before Next.js has served its first request (for example in onInit), where it logs a warning.

Changes the hooks cannot see stay cached until revalidate runs out: direct database writes, and writes from another process or server instance (the Payload CLI, seed scripts, a second app instance). That's why revalidate defaults to 60 seconds. Use revalidate: false only if every change goes through Payload in the same process, or clear the tag yourself with revalidateTag('payload-feature-flags', { expire: 0 }) (on Next.js 15, revalidateTag('payload-feature-flags')). Outside a Next.js server, lookups are not cached.

For another store (Redis, in-memory, ...) pass an object with wrap(key, load) and invalidate(). The FeatureFlagsCache type, createNextCache() and DEFAULT_CACHE_TAG are exported from the root entry point.

Admin dashboard

/admin/feature-flags-overview lists every flag with search (name, description, tags), sorting, totals (enabled, disabled, rolling out, A/B tests), and inline toggles for enabled and rolloutPercentage. It needs a logged-in user with read access to the collection; editing needs update access. With enableCustomListView: true the same dashboard replaces the collection's list view.

The views are exported from @xtr-dev/payload-feature-flags/views (FeatureFlagsView, FeatureFlagsOverviewView).

REST API

The collection is a normal Payload collection, so Payload's REST and GraphQL APIs work as usual and respect its access control:

curl 'http://localhost:3000/api/feature-flags?where[name][equals]=new-dashboard'

Troubleshooting

  • Dashboard or list view shows a missing component error: run payload generate:importmap.
  • Client hooks return nothing or an error: the visitor needs read access to the collection, or use publicEndpoint with source: 'public'.
  • A changed flag still shows its old value: with cache on, a change from outside the app process shows after revalidate seconds. See Caching.

Development

pnpm install
pnpm dev     # demo app at http://localhost:3000, SQLite, login [email protected] / test
pnpm test    # Vitest
pnpm lint
pnpm build

See dev/README.md for the demo app.

License

MIT. See CHANGELOG.md for changes, and open an issue for bugs and questions.

Similar plugins