Feature Flags Plugin
Runtime feature switches, deterministic rollouts, and user segment targeting
Best for
Teams shipping gradual releases, beta access, and kill switches.
Control feature availability without redeploying your application.

BTST supplies
- Boolean flags, deterministic percentage rollouts, and user segment targeting
- Flag management pages, React evaluation hooks, and server operations
- A configurable definition cache and bounded ephemeral evaluation logs
You supply
- A BTST database adapter and administrator authorization rules
- Evaluation context and a stable user or session identifier for rollouts
- Application rendering for enabled and disabled feature variants
You own and customize
Flag definitions stay in your database. Your application supplies administrator access rules, evaluation context, and feature variants.
Compatibility and dependencies
Maintained: Next.js 15+ App Router, React Router v7, TanStack Start.
Requires: A BTST database adapter.
External services: None required.
From registration to result
A semantic workflow, not a setup shortcut
- 1Define a flag
Choose a boolean switch, percentage rollout, or user segment rules.
- 2Evaluate in your app
Read a flag through a server operation or the useFlag React hook.
- 3Adjust availability
Toggle or update a flag and inspect recent evaluations.
Feature Flags controls feature availability without redeployments. Use boolean flags as kill switches, percentage rollouts for gradual releases, and segment rules for beta users. Definitions live in your BTST database; evaluation reads a short-lived in-process cache. Recent evaluations are retained in memory.
Setup
Install the independently versioned package with Core v6:
pnpm add --save-exact @btst/stack@6.2.0 @btst/plugin-feature-flags@1.2.0The package preserves existing flag records and rollout assignments. It does not require another feature package or the optional standalone Components package.
Register both plugins under the canonical featureFlags key. Follow the
installation guide for your database adapter, framework router,
and shared server/client authorization adapters.
import { createBackendStack } from "@btst/stack/api"
import { featureFlagsBackendPlugin } from "@btst/plugin-feature-flags/api"
export const myStack = createBackendStack({
basePath: "/api/data",
adapter,
auth: serverAuth,
plugins: {
featureFlags: featureFlagsBackendPlugin({
cacheTtlMs: 30_000,
evaluationLogLimit: 100,
hooks: {
onAfterToggle: async (flag, enabled) => {
console.log(`Flag ${flag.key}: ${enabled}`)
},
},
}),
},
})import { createClientStack } from "@btst/stack/client"
import { featureFlagsClientPlugin } from "@btst/plugin-feature-flags/client"
export function getStackClient(queryClient, origin: string) {
return createClientStack({
api: { baseURL: origin, basePath: "/api/data" },
site: { baseURL: origin, basePath: "/pages" },
queryClient,
plugins: { featureFlags: featureFlagsClientPlugin() },
})
}@import "@btst/plugin-feature-flags/css";Mount the resolved client stack in StackProvider with your framework router and
client auth adapter. Keep protected administration routes dynamically rendered;
for Next.js, put them under a layout with dynamic = "force-dynamic".
Authorization
Register featureFlagsPermissions from
@btst/plugin-feature-flags/permissions with your application's shared
authorization contract. For an identity with a role field:
permissions: [featureFlagsPermissions] as const,
rules: ({ featureFlags }) => [
featureFlags.flags.read.when(({ identity }) => identity?.role === "admin"),
featureFlags.flags.create.when(({ identity }) => identity?.role === "admin"),
featureFlags.flags.update.when(({ identity }) => identity?.role === "admin"),
featureFlags.flags.toggle.when(({ identity }) => identity?.role === "admin"),
featureFlags.flags.archive.when(({ identity }) => identity?.role === "admin"),
featureFlags.evaluations.read.when(({ identity }) => identity?.role === "admin"),
],Evaluation operations and HTTP endpoints are public: they expose boolean results,
assigned variant keys, and assigned payloads
and do not consult authorization rules. Bulk evaluation also exposes active flag
keys. Their permission facts distinguish scope: "single" with a key from
scope: "all", but those descriptors do not restrict public access. Browser
context is caller supplied and untrusted. Feature flags control presentation and
rollout; enforce authorization separately for protected data and operations.
Evaluation logs may include emails and user IDs, so restrict their readership.
Flag types
- Boolean: an enabled flag evaluates to
true. - Rollout: an enabled flag selects a stable percentage from 0 to 100. The
assignment includes the flag key and
userId, falling back tosessionId, thenanonymous. Supply a stable ID to distribute users or sessions; anonymous requests without either identifier share one assignment. - Segment: an enabled flag evaluates to
trueonly when every rule matches. UseequalsorinforuserIdandemail, andcontainsorinfor tags. Values inside aninlist are alternatives.
For example, target users tagged beta whose email is in an approved list:
await myStack.trusted.featureFlags.createFlag({
key: "new-checkout",
name: "New checkout",
type: "segment",
enabled: true,
tags: ["beta", "checkout"],
segments: [
{ field: "tags", operator: "contains", value: "beta" },
{ field: "email", operator: "in", value: ["tester@example.com"] },
],
})Disabled, archived, and missing flags evaluate to false. Keys remain reserved
when archived. Segment flags require at least one rule. Organizing tags on the
flag definition are separate from targeting tags supplied in evaluation context.
Weighted variants
Any flag type can define optional weighted alternatives. Existing boolean
evaluations are unchanged: variants are assigned only after the flag evaluates to
true. Use the dashboard's Variants controls to add keys, weights, and optional
JSON payloads, then Preview saved variants to try a user or session and see
the assignment in the evaluation log.
await myStack.trusted.featureFlags.createFlag({
key: "checkout-layout",
name: "Checkout layout",
enabled: true,
variants: [
{ key: "control", weight: 30, payload: "classic" },
{ key: "compact", weight: 70, payload: { columns: 1 } },
],
})
const { result, variant, payload } = await myStack.forRequest(request)
.operations.featureFlags.evaluateVariant({
key: "checkout-layout",
context: { userId: session.userId },
})Variant keys must be unique, non-empty strings of up to 100 characters.
Weights are finite numbers from 0 to 100 and must sum to 100, including decimal
weights. Zero-weight alternatives receive no assignments. An empty variants
array removes variants. Payloads may be strings, numbers, booleans, or JSON
objects (including nested arrays and nulls); top-level arrays and null are not
accepted. Payloads are public to evaluation clients; never store secrets in them.
Assignment uses the flag key and userId, falling back to sessionId, then
anonymous, in a separate bucket from percentage rollout. The same definition
and identity produce the same assignment on server, browser, and edge. Editing
weights, keys, or ordering can reassign subjects. Disabled, archived, missing,
untargeted flags and flags without variants return variant: null without a
payload. result still reports boolean eligibility.
The pure evaluateFlagVariant(flag, context) export from
@btst/plugin-feature-flags/evaluate returns the same assignment without logs or
hooks. Database users must apply their adapter's additive schema migration for
the new serialized flag.variants string field (default "[]"). Existing records
without variants are read as empty lists; existing rollout buckets are preserved.
Experiment measurement with Analytics
Weighted assignment alone is not exposure measurement. The opt-in Analytics experiment bridge records exposure only after the application explicitly reports that the assigned experience was shown. Repeated flag evaluation does not increase exposed subjects. Both packages remain independently installable.
Use evaluateExperimentVariant({ key, context }) from request-bound or trusted
Feature Flags operations inside Analytics' server resolver. Its public HTTP
equivalent is GET /feature-flags/experiment-variant/:key with the same encoded
context as other evaluation endpoints. It preserves the
existing deterministic weighted assignment and adds a stable
configurationVersion fingerprint of the saved flag definition. Changed weights
or other evaluation settings produce a separate report version. Missing or
ineligible assignments have no measurable variant and create no exposure.
Supply the same permitted anonymous session used for Analytics conversion events
as context.sessionId by default. In the browser, obtain this key with
tracker.getSessionId() or the configured default getAnalyticsSessionId()
helper before evaluating and displaying a variant; then report expose() after
that experience is shown, passing its returned configurationVersion to
expose(experimentKey, configurationVersion). The bridge rejects exposure if the
saved definition changed after evaluation. Stronger targeting identity must be an explicit
application mapping in the server resolver; never persist raw user IDs or email
addresses as Analytics attribution keys. Browser variant labels cannot override
the server-resolved assignment and are not an authoritative business or payment
signal. The bridge limits attribution to one session within one UTC day and its
configured window; see the Analytics documentation for deduplication and
configuration-change rules.
Server-side evaluation
Use request-scoped operations in Server Components and API routes. Evaluation is public, while management operations use the shared authorization policy. These calls stay in process without an HTTP round trip:
const isEnabled = await myStack.forRequest(request).operations.featureFlags.evaluate({
key: "new-checkout",
context: { userId: session.userId, email: session.email, tags: ["beta"] },
})
const values = await myStack.forRequest(request).operations.featureFlags.evaluateAll({
context: { sessionId: "stable-session-id" },
})Explicitly trusted jobs and build scripts can use
myStack.trusted.featureFlags.evaluate({ key, context }). Trusted operations
bypass access checks; only use them after the calling application has established
the appropriate trust boundary.
The pure evaluator is available separately for already-resolved definitions:
import { evaluateFlag } from "@btst/plugin-feature-flags/evaluate"
const value = evaluateFlag(flag, { userId: "user-123" })It has no database dependency and can run at the edge. Pure evaluation does not record a log or call lifecycle hooks.
React hooks
Use useFlag inside StackProvider. It returns a React Query result whose data
is the evaluated boolean:
"use client"
import { useFlag } from "@btst/plugin-feature-flags/client/hooks"
export function Checkout({ userId }: { userId: string }) {
const { data: enabled = false, isPending, error } = useFlag("new-checkout", { userId })
if (isPending) return <p>Loading checkout…</p>
if (error) return <p>Checkout availability could not be loaded.</p>
return enabled ? <NewCheckout /> : <LegacyCheckout />
}useFlags({ includeArchived: true }) reads definitions for management and requires
flag read permission. The same hooks entry exports create, update, toggle, archive,
and evaluation-log hooks. Management mutations invalidate cached definitions,
values, and logs in the current query client.
useFeatureFlagVariant returns a React Query result with the boolean result,
assigned key, and optional payload. It uses the same identity and transport cache
partitioning and visible-tab refresh interval as useFlag. Definition edits
invalidate both hooks immediately in the current query client.
import { useFeatureFlagVariant } from "@btst/plugin-feature-flags/client/hooks"
const { data, isPending, error } = useFeatureFlagVariant("checkout-layout", { userId })
if (isPending) return <p>Loading layout…</p>
if (error) return <p>Layout could not be loaded.</p>
return data?.variant === "compact" ? <CompactCheckout /> : <ClassicCheckout />HTTP evaluation
| Method | Endpoint | Result |
|---|---|---|
| GET | /api/data/feature-flags/evaluate/:key | Boolean |
| GET | /api/data/feature-flags/evaluate | Object mapping active flag keys to booleans |
| GET | /api/data/feature-flags/variant/:key | { result: boolean, variant: string | null, payload?: ... } |
All evaluation endpoints accept an optional context query parameter containing base64
encoded UTF-8 JSON, such as { "userId": "user-123", "tags": ["beta"] }. Invalid
context is rejected. Definitions and evaluation logs use separate protected
management endpoints under /api/data/feature-flags/flags.
Cache and evaluation logs
cacheTtlMs defaults to 30 seconds. Warm evaluations avoid database reads.
Creating, updating, toggling, or archiving a flag through plugin operations
invalidates the cache immediately in that plugin instance. Other processes see
changes after their TTL expires; direct database changes also wait for expiry.
Set the TTL to zero to disable caching.
evaluationLogLimit bounds recent evaluations per flag and defaults to 100.
Memory use grows with the number of evaluated flag definitions. Logs are
instance-local and ephemeral: restarts clear them and different server instances
have separate histories. Use hooks.onEvaluate to send exposures to your analytics or
audit system when persistent storage is required. Hooks run after authorization;
onBeforeToggle can throw to prevent a toggle.
Every evaluation path (including boolean and bulk evaluation) records the assigned
variant key or null in FlagEvaluation. The existing onEvaluate callback
keeps its argument order; its fourth argument now includes variant:
onEvaluate: (flag, result, context, { request, variant }) => {
analytics.capture({ flag: flag.key, result, variant, userId: context.userId })
}SSG and ISR
Administration is dynamic. A static consumer can evaluate trusted flag values at build time; its result remains in the generated HTML until regeneration:
export const revalidate = 30
export default async function CheckoutPage() {
const enabled = await myStack.trusted.featureFlags.evaluate({ key: "new-checkout" })
return enabled ? <NewCheckout /> : <LegacyCheckout />
}ISR timing and the definition TTL both affect when a change becomes visible. Use a client hook or a dynamic server route when the page must observe changes without static regeneration.
Admin routes
Routes are relative to the stack's site base path, such as /pages.
| Route | Path | Purpose |
|---|---|---|
flags | /feature-flags | List, live toggle, archive, and organizing tags |
newFlag | /feature-flags/new | Create a flag |
editFlag | /feature-flags/:key | Edit configuration and targeting rules |
flagDetail | /feature-flags/:key/log | Inspect recent evaluations and context |
Configuration reference
Prop
Type
Prop
Type
Prop
Type
Page-scoped presentation
StackProvider accepts overrides.featureFlags.pageOverrides with the route keys flags, newFlag, and editFlag. Each supports Rollout, a component receiving { percent: number }. It changes the rollout display while retaining the flag controls and validation.
overrides={{
featureFlags: {
pageOverrides: {
flags: { Rollout: ({ percent }) => <strong>{percent}% enabled</strong> },
},
},
}}This changes the management list; new/edit forms keep the built-in rollout meter. A missing component falls back to the built-in display. The flagDetail evaluation log has no rollout display and accepts no slot. Whole-page replacements and localization keep their existing behavior. A standalone rollout display receives no page scope by default.