Skip to main content

Feature Flags in Frontend Apps: Progressive Delivery, Rollouts, and A/B Testing

A practical guide to feature flags for web apps. Learn the types of flags, how flag evaluation and percentage rollouts work, how to use flags in React and server-rendered apps without flicker, how OpenFeature avoids vendor lock-in, and how to test, clean up, and govern flags before they turn into technical debt.

Table of Contents


Introduction

Most teams discover feature flags the same way. A big feature has been living on a long-running branch for six weeks, the merge is painful, and the release goes out on a Friday with everyone watching the error dashboard. Something breaks, and the only way back is a revert and a full redeploy.

Feature flags break that coupling between deploying code and releasing features. Code ships to production continuously, hidden behind a flag. Turning the feature on becomes a configuration change that takes seconds, can target a single user or 5% of traffic, and can be undone just as quickly.

That flexibility comes with costs. Flags add branches to your code, make testing harder, can cause UI flicker in server-rendered apps, and pile up as debt if nobody removes them. This guide covers both sides: how flags work under the hood, how to use them well in frontend and full-stack apps, and how to keep them from taking over your codebase.

If your team uses trunk-based development, flags are what make it practical. Our Git workflows guide covers that side of the story.


What a Feature Flag Actually Is

At its simplest, a feature flag is a conditional whose value is decided at runtime, outside the code:

if (flags.isEnabled("new-checkout", user)) {
return <NewCheckout />;
}
return <LegacyCheckout />;

Three pieces make this work:

  1. A flag definition: the flag’s key, its possible values (variants), and its default
  2. Rules: who gets which variant, based on attributes like user ID, country, plan, or a random percentage
  3. An evaluation context: the facts about the current request or user that rules are checked against
Flag definition + Rules + Evaluation context → Evaluated value
"new-checkout" "10% of { userId: "u_42", true
default: false users" country: "DE" }

Flags aren’t limited to booleans. A flag can return a string ("control", "variant-a"), a number (a page size or timeout), or a JSON object (a whole configuration block).


The Four Types of Flags

Not all flags are the same, and treating them the same is how codebases end up with hundreds of stale toggles. A widely used categorization splits them by how long they live and how often they change:

TypePurposeLifetimeExample
ReleaseHide unfinished or unreleased workDays to weeksnew-checkout
ExperimentA/B test variants and measure impactWeekspricing-page-layout
OperationalKill switches and load-sheddingLong-liveddisable-recommendations
PermissionEnable features for specific plans or usersLong-livedbeta-ai-assistant, plan-enterprise-sso

The distinction matters because each type needs different handling:

  • Release flags should be removed soon after the feature reaches 100%. They’re the main source of flag debt.
  • Experiment flags need consistent assignment and analytics, and are removed once the experiment concludes.
  • Operational flags are deliberately permanent and must work even when other systems are degraded.
  • Permission flags are often better modeled as entitlements in your own database than as flags in a third-party tool, since they’re business logic, not deployment state.

Name or tag flags by type so the intent is clear months later.


How Flag Evaluation Works

There are two broad architectures, and the choice affects performance, privacy, and how flags behave on the client.

Remote Evaluation

The client sends its context to a flag service, and the service returns the evaluated values:

Browser ── { userId, country, plan } ──▶ Flag service
Browser ◀── { "new-checkout": true, ... } ── Flag service
  • ✅ Rules and targeting lists stay private on the server
  • ✅ The client downloads only the results, not the rules
  • ❌ Requires a network call before flags are known
  • ❌ Changing the context (like logging in) means re-fetching

Most client-side SDKs work this way.

Local Evaluation

The SDK downloads the full set of rules and evaluates them in-process:

Server SDK ── fetch rules (cached, streamed updates) ──▶ Flag service
Server SDK: evaluate(rules, context) → value (no network call per evaluation)
  • ✅ Evaluation is essentially free, so you can check flags on every request
  • ✅ Keeps working from cached rules if the flag service goes down
  • ❌ Exposes all rules and targeting data to wherever the SDK runs

Server-side SDKs usually work this way. Never ship local evaluation to the browser if your rules contain anything sensitive, like customer email lists or unreleased plan names.


Targeting Rules

Rules are evaluated top to bottom, and the first match wins:

{
"key": "new-checkout",
"variants": { "on": true, "off": false },
"defaultVariant": "off",
"rules": [
{
"if": { "attribute": "email", "endsWith": "@ourcompany.com" },
"variant": "on"
},
{
"if": { "attribute": "userId", "in": ["u_101", "u_202"] },
"variant": "on"
},
{
"if": { "attribute": "country", "in": ["NZ"] },
"rollout": { "on": 25, "off": 75 }
}
]
}

This flag turns the new checkout on for employees, for two named beta users, and for 25% of users in New Zealand. Everyone else gets the default.

Common targeting attributes:

  • User or account ID for individual targeting and consistent rollouts
  • Organization or tenant ID so that everyone at a company sees the same thing (important for B2B apps)
  • Plan or tier for entitlement-style flags
  • Country, locale, platform, app version for regional or client-specific rollouts
  • Internal user for dogfooding

Percentage Rollouts and Consistent Hashing

A naive percentage rollout uses Math.random():

// ❌ Different result on every page load
const enabled = Math.random() < 0.1;

A user would see the new feature, refresh, and see the old one. Rollouts need to be sticky: the same user should get the same answer every time. The standard approach is to hash the flag key and a stable identifier into a bucket:

// A small, fast, non-cryptographic hash (FNV-1a, 32-bit)
function fnv1a(str) {
let hash = 0x811c9dc5;
for (let i = 0; i < str.length; i++) {
hash ^= str.charCodeAt(i);
hash = Math.imul(hash, 0x01000193);
}
return hash >>> 0;
}
function bucket(flagKey, userId) {
return fnv1a(`${flagKey}:${userId}`) % 10_000; // 0..9999, i.e. 0.01% precision
}
function inRollout(flagKey, userId, percentage) {
return bucket(flagKey, userId) < percentage * 100;
}
inRollout("new-checkout", "u_42", 10); // same answer every time for u_42

Two properties make this work:

  • Including the flag key in the hash means a user who lands in the first 10% of one flag isn’t automatically in the first 10% of every flag. Otherwise the same unlucky users would get every risky feature first.
  • Increasing the percentage only adds users. A user in the bucket at 10% stays in at 25%, 50%, and 100%, so nobody flips back and forth during a rollout.

What About Anonymous Users?

Before login, there’s no user ID. Generate a random ID on first visit, store it in a first-party cookie, and use it as the bucketing key. When the user logs in, keep using the anonymous ID for any in-flight experiment, or you’ll reassign them to a different variant mid-session. Many flag tools support “aliasing” an anonymous ID to a user ID for exactly this reason.


Building a Minimal Flag System

You don’t need a vendor to get started. Here’s a small, typed flag evaluator that supports defaults, overrides, and rollouts:

flags/definitions.ts
export const flagDefinitions = {
"new-checkout": {
type: "release",
owner: "payments-team",
defaultValue: false,
rolloutPercentage: 10,
allowList: ["u_101", "u_202"],
},
"search-results-page-size": {
type: "operational",
owner: "search-team",
defaultValue: 20,
},
} as const;
export type FlagKey = keyof typeof flagDefinitions;
export type FlagValue<K extends FlagKey> =
(typeof flagDefinitions)[K]["defaultValue"];
flags/evaluate.ts
import { flagDefinitions, type FlagKey, type FlagValue } from "./definitions";
export interface EvaluationContext {
userId?: string;
overrides?: Partial<Record<FlagKey, unknown>>;
}
export function evaluate<K extends FlagKey>(
key: K,
ctx: EvaluationContext,
): FlagValue<K> {
const def = flagDefinitions[key];
// 1. Explicit overrides (for QA, tests, or a ?flags= debug param in non-prod)
if (ctx.overrides && key in ctx.overrides) {
return ctx.overrides[key] as FlagValue<K>;
}
// 2. Allow list
if ("allowList" in def && ctx.userId && def.allowList.includes(ctx.userId)) {
return true as FlagValue<K>;
}
// 3. Percentage rollout
if ("rolloutPercentage" in def && ctx.userId) {
return inRollout(key, ctx.userId, def.rolloutPercentage) as FlagValue<K>;
}
return def.defaultValue as FlagValue<K>;
}

Keeping definitions in code has real advantages: flags are type-checked, reviewed in pull requests, and easy to find and delete. The downside is that changing a flag means a deploy. Many teams start here and move flag values (not definitions) to a remote config store once they need to change them without deploying.


OpenFeature: A Vendor-Neutral API

Every flag vendor has its own SDK with its own API. If you call launchDarkly.variation(...) or posthog.isFeatureEnabled(...) in 400 places, switching vendors means touching 400 places.

OpenFeature is a CNCF project that defines a standard flag evaluation API. Your code talks to OpenFeature, and a provider connects it to whatever backend you use: a vendor, an open-source service like flagd, or your own in-house system.

import { OpenFeature } from "@openfeature/web-sdk";
import { SomeVendorProvider } from "some-vendor-openfeature-provider";
await OpenFeature.setProviderAndWait(
new SomeVendorProvider({ clientKey: "..." }),
);
await OpenFeature.setContext({
targetingKey: user.id,
plan: user.plan,
country: user.country,
});
const client = OpenFeature.getClient();
const showNewCheckout = client.getBooleanValue("new-checkout", false);
const pageSize = client.getNumberValue("search-results-page-size", 20);

Key concepts:

  • targetingKey is the stable identifier used for bucketing
  • Every evaluation takes a default, which is returned if the provider is unavailable or the flag doesn’t exist. Your app never crashes because a flag service is down.
  • Hooks let you add logging, metrics, or validation around every evaluation in one place
  • Separate web and server SDKs reflect the two evaluation models: the web SDK evaluates against a static context set once, while server SDKs take a context per evaluation

Even if you never switch vendors, the abstraction is useful for testing, since you can swap in an in-memory provider.


Feature Flags in React

A Typed Hook

Whatever backend you use, wrap it in a small hook so components never touch the SDK directly:

flags/FlagProvider.tsx
import { createContext, useContext } from "react";
import type { FlagKey, FlagValue } from "./definitions";
type FlagValues = { [K in FlagKey]: FlagValue<K> };
const FlagContext = createContext<FlagValues | null>(null);
export function FlagProvider({
values,
children,
}: {
values: FlagValues;
children: React.ReactNode;
}) {
return <FlagContext.Provider value={values}>{children}</FlagContext.Provider>;
}
export function useFlag<K extends FlagKey>(key: K): FlagValue<K> {
const values = useContext(FlagContext);
if (!values) throw new Error("useFlag must be used inside <FlagProvider>");
return values[key];
}
function CheckoutButton() {
const newCheckout = useFlag("new-checkout");
return newCheckout ? <NewCheckoutButton /> : <LegacyCheckoutButton />;
}

If you use OpenFeature, its React SDK provides equivalent hooks like useBooleanFlagValue("new-checkout", false) and re-renders components when flag values change.

Keep Flag Checks at the Edges

Check a flag once, as high in the tree as makes sense, and branch to entirely separate components. Avoid sprinkling the same flag through dozens of leaf components:

// ❌ The flag leaks into every detail of the page
function CheckoutPage() {
const v2 = useFlag("new-checkout");
return (
<>
<Header compact={v2} />
{v2 ? <AddressFormV2 /> : <AddressForm />}
<Summary showTaxBreakdown={v2} />
{v2 && <ExpressPay />}
</>
);
}
// ✅ One branch point, two clean implementations
function CheckoutPage() {
return useFlag("new-checkout") ? <CheckoutV2 /> : <CheckoutV1 />;
}

The second version is easier to test and, when the rollout finishes, cleanup is deleting CheckoutV1 and one line.

Lazy-Load Flagged Features

Don’t ship the new feature’s code to users who can’t see it:

import { lazy, Suspense } from "react";
const CheckoutV2 = lazy(() => import("./CheckoutV2"));
function CheckoutPage() {
if (!useFlag("new-checkout")) return <CheckoutV1 />;
return (
<Suspense fallback={<CheckoutSkeleton />}>
<CheckoutV2 />
</Suspense>
);
}

Server Rendering and the Flicker Problem

In a purely client-side setup, flags are fetched after the page loads. The user first sees the default (old) UI, then the flags arrive and the page re-renders into the new one. This flicker is jarring, hurts Cumulative Layout Shift, and in experiments it biases results.

The fix is to evaluate flags on the server and send the results with the HTML:

// app/layout.tsx (Next.js App Router, server component)
import { cookies } from "next/headers";
import { evaluateAllFlags } from "@/flags/server";
import { FlagProvider } from "@/flags/FlagProvider";
import { getCurrentUser } from "@/auth";
export default async function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
const user = await getCurrentUser();
const anonymousId = (await cookies()).get("anon_id")?.value;
const flags = await evaluateAllFlags({ userId: user?.id ?? anonymousId });
return (
<html lang="en">
<body>
<FlagProvider values={flags}>{children}</FlagProvider>
</body>
</html>
);
}

The server renders the correct variant from the start, and the client hydrates with the same values, so there’s no mismatch. A few important details:

  • Pass only evaluated values to the client, never the rules
  • Pass only the flags the client needs, not every flag in the system
  • Flags make pages dynamic. A page that varies per user can’t be cached as a single static HTML file at the CDN. Either vary the cache key on the variant (only feasible for a handful of variants), or keep the flagged part as a small client or streamed component. Our HTTP caching guide explains why personalized responses must not be cached publicly.

In React Server Components, you can evaluate flags directly in the component that needs them, which keeps the unused variant’s code entirely off the client. See our Server Components guide for more.

If You Must Evaluate on the Client

For purely client-rendered apps, you have a few options:

  • Bootstrap flags by inlining the evaluated values in the initial HTML, rendered by whatever serves your index.html
  • Cache the last known values in localStorage and render with them immediately, then update in the background
  • Hold rendering of only the flagged region behind a skeleton until flags load, with a short timeout that falls back to the default

Evaluating Flags at the Edge

Edge middleware (in Vercel, Cloudflare Workers, Netlify, and similar platforms) runs before your page is rendered or served from cache. That makes it a good place to assign experiment variants and route to statically generated pages:

middleware.ts
import { NextResponse, type NextRequest } from "next/server";
import { inRollout } from "@/flags/rollout";
export function middleware(request: NextRequest) {
let anonId = request.cookies.get("anon_id")?.value;
const response = NextResponse.next();
if (!anonId) {
anonId = crypto.randomUUID();
response.cookies.set("anon_id", anonId, {
httpOnly: true,
sameSite: "lax",
maxAge: 60 * 60 * 24 * 365,
});
}
if (request.nextUrl.pathname === "/pricing") {
const variant = inRollout("pricing-layout", anonId, 50) ? "b" : "a";
const url = request.nextUrl.clone();
url.pathname = `/pricing/${variant}`;
return NextResponse.rewrite(url, { headers: response.headers });
}
return response;
}

Both /pricing/a and /pricing/b can be fully static and CDN-cached, while each user consistently sees one of them. The user’s URL stays /pricing. This pattern gives you experiments without giving up static performance.


Progressive Delivery in Practice

Progressive delivery is the practice of releasing a change to gradually larger audiences while watching for problems. Flags are the mechanism.

A typical rollout plan for a risky feature:

Stage 1: Internal users only (dogfood for a few days)
Stage 2: 1% of users (watch errors and key metrics)
Stage 3: 10% (watch for a day)
Stage 4: 50% (watch for a day)
Stage 5: 100% (keep the flag a week as a kill switch)
Stage 6: Remove the flag and old code path

At each stage, compare the metrics of users with the flag on against users with it off:

  • Error rate and new error types in your error tracker
  • Core Web Vitals, particularly INP and LCP, for the flagged pages
  • Business metrics like conversion or task completion
  • Support tickets mentioning the feature

Tag your errors and analytics events with active flag values, so you can filter by variant:

Sentry.setTag("flag.new-checkout", String(flags["new-checkout"]));
analytics.track("checkout_completed", {
orderValue,
flags: { "new-checkout": flags["new-checkout"] },
});

Kill Switches

Operational flags that disable expensive or fragile features are cheap insurance:

if (!flags["recommendations-enabled"]) {
return null; // hide the widget entirely if the recommendations API is struggling
}

Kill switches must fail safe. If the flag service is unreachable, the default should be the safe behavior. For a kill switch, that usually means the feature stays on (the normal state), with the flag used only to actively turn it off. Decide this deliberately for each operational flag.


A/B Testing with Flags

An experiment is a multivariate flag plus measurement. The flag assigns variants; analytics measures outcomes.

const variant = client.getStringValue("pricing-layout", "control"); // "control" | "annual-first"
// Record exposure at the moment the user actually sees the variant
useEffect(() => {
analytics.track("experiment_exposure", {
experiment: "pricing-layout",
variant,
});
}, [variant]);

A few things separate useful experiments from misleading ones:

  • Log exposure when the user actually sees the variant, not when the flag is evaluated. If you evaluate every flag on page load but the pricing table is below the fold, users who never scrolled will dilute the results.
  • Keep assignment sticky across sessions and devices by bucketing on a stable ID.
  • Decide the success metric and sample size before starting, and don’t stop the test the moment results look good. Peeking at results and stopping early is the most common way to “find” an effect that isn’t real.
  • Avoid running overlapping experiments on the same UI without accounting for interactions between them.
  • Remove the flag when the test ends. Ship the winner as plain code.

Testing Code Behind Flags

Every boolean flag doubles the number of code paths. Two flags make four. You can’t test every combination, so be deliberate.

Unit and Component Tests

Make flag values an explicit input so tests can set them:

import { render, screen } from "@testing-library/react";
import { FlagProvider } from "@/flags/FlagProvider";
import { defaultFlags } from "@/flags/defaults";
function renderWithFlags(ui: React.ReactElement, overrides = {}) {
return render(
<FlagProvider values={{ ...defaultFlags, ...overrides }}>
{ui}
</FlagProvider>,
);
}
test("shows express pay in the new checkout", () => {
renderWithFlags(<CheckoutPage />, { "new-checkout": true });
expect(
screen.getByRole("button", { name: /express pay/i }),
).toBeInTheDocument();
});
test("legacy checkout still works", () => {
renderWithFlags(<CheckoutPage />, { "new-checkout": false });
expect(
screen.getByRole("button", { name: /place order/i }),
).toBeInTheDocument();
});

End-to-End Tests

For Playwright or Cypress, support forcing flags in non-production environments, for example via a cookie your server reads:

test("new checkout flow", async ({ page, context }) => {
await context.addCookies([
{
name: "flag_overrides",
value: JSON.stringify({ "new-checkout": true }),
url: "http://localhost:3000",
},
]);
await page.goto("/checkout");
await expect(page.getByRole("heading", { name: "Checkout" })).toBeVisible();
});

Never honor override cookies or query parameters in production for flags that gate access or permissions.

Which Combinations to Test

  • The current production state (what most users see)
  • The target state (everything about to be turned on)
  • Each in-progress flag toggled individually against the production state

See our testing strategies guide and Playwright vs Cypress comparison for broader context.


Security: What Not to Put in Client-Side Flags

Anything that reaches the browser is public. That has a few consequences:

  • A client-side flag is not access control. If a flag hides the “Admin” button, a user can flip it in DevTools. The server must enforce permissions on every request regardless of the flag. Our authentication and authorization guide covers server-side enforcement.
  • Flag keys and variant names leak plans. A flag called launch-acquisition-of-competitor-x in your JavaScript bundle is a press leak. Use neutral names for sensitive work, and only send the client the flags it needs.
  • Rules can contain personal data. Allow lists of emails or user IDs must not be shipped to browsers. Use remote evaluation for client-side flags.
  • Unreleased code is still in the bundle. Hiding a feature behind a flag doesn’t hide its code. If the feature itself is confidential, lazy-load it from a route that checks authorization, or keep it server-side until launch.

Flag Debt and Cleanup

Flags are meant to be temporary, but without process they never leave. Old flags make code harder to read, multiply test paths, and occasionally cause outages when someone toggles a flag nobody remembers.

Give Every Flag an Owner and an Expiry

"new-checkout": {
type: "release",
owner: "payments-team",
createdAt: "2026-08-20",
expiresAt: "2026-10-31",
ticket: "PAY-1423",
defaultValue: false,
},

Fail CI on Expired Release Flags

A small script can enforce expiry dates:

scripts/check-flags.ts
import { flagDefinitions } from "../src/flags/definitions";
const today = new Date().toISOString().slice(0, 10);
const expired = Object.entries(flagDefinitions).filter(
([, def]) =>
def.type === "release" && "expiresAt" in def && def.expiresAt < today,
);
if (expired.length > 0) {
console.error("Expired release flags (remove them or extend the date):");
for (const [key, def] of expired)
console.error(` ${key} (owner: ${def.owner})`);
process.exit(1);
}

Also detect flags that are defined but no longer referenced in code, and flags referenced in code that no longer exist in your flag service. Both are easy to find with a search across the codebase for each flag key.

Make Removal Part of the Feature

Create the cleanup ticket when you create the flag, and treat the feature as unfinished until the flag is gone. Removing a release flag should be a small diff: delete the old component, delete the branch, delete the definition. If it isn’t small, the flag was checked in too many places.


Build vs Buy

ApproachGood forTrade-offs
Flags in code / env varsSmall teams, release flags, few rolloutsEvery change needs a deploy; no targeting UI
Remote config you buildSimple rollouts and kill switches with existing infraYou own reliability, UI, audit logs, and SDKs
Open-source serviceSelf-hosting, data residency, avoiding per-seat pricingYou run and upgrade it
Commercial vendorExperiments, complex targeting, non-engineers managing flagsCost, vendor lock-in (reduced with OpenFeature)

Questions that usually decide it:

  • Do non-engineers need to change flags? If product managers run rollouts and experiments, you want a UI, audit log, and approvals.
  • Do you run statistically rigorous experiments? Building experiment analysis well is hard; vendors with built-in stats save a lot of effort.
  • What happens when the flag service is down? Whatever you choose, make sure SDKs cache values and every evaluation has a safe default.

Common Pitfalls

❌ Pitfall 1: Using Math.random() for Rollouts

Users flip between variants on every load. Hash a stable ID together with the flag key.

❌ Pitfall 2: Client-Side Flicker

Evaluating flags after render shows the wrong UI first. Evaluate on the server or at the edge, or bootstrap values into the initial HTML.

❌ Pitfall 3: Treating Flags as Authorization

Hiding a button isn’t security. Enforce permissions on the server.

❌ Pitfall 4: Bucketing B2B Users Individually

Two people at the same company seeing different UIs causes confusion and support tickets. Bucket on the organization ID for B2B products.

❌ Pitfall 5: Flags Checked in Dozens of Places

Every extra check makes cleanup harder and increases the chance of inconsistent UI. Branch once, high in the tree.

❌ Pitfall 6: Never Removing Flags

Release flags left at 100% are dead code with a hidden “break production” switch. Set expiry dates and enforce them in CI.

❌ Pitfall 7: Unsafe Defaults

If the flag service is unreachable, every evaluation returns its default. Make sure the default is a state you’re happy to run in.

❌ Pitfall 8: Logging Exposure at Evaluation Time

Experiments become diluted with users who never saw the variant. Log exposure when the variant is actually displayed.


Checklist


Conclusion

Feature flags turn releases from high-stakes events into routine, reversible configuration changes. They let you merge to main continuously, test in production with real users, roll out gradually, run experiments, and switch off a failing feature in seconds instead of minutes.

Key Takeaways:

  • Flags separate deploy from release, which makes continuous delivery and trunk-based development practical
  • Different flag types need different lifecycles: release and experiment flags are temporary, operational and permission flags are long-lived
  • Remote evaluation keeps rules private for client-side flags; local evaluation is fast for servers
  • Consistent hashing of the flag key and a stable ID makes rollouts sticky and monotonic
  • OpenFeature gives you a vendor-neutral API with safe defaults and testable providers
  • Server or edge evaluation eliminates flicker, but personalized pages need careful caching
  • Branch once, high in the tree, and lazy-load flagged code
  • Experiments need exposure logging, sticky assignment, and pre-decided success metrics
  • Client-side flags are public and never a substitute for server-side authorization
  • Flag debt is real: owners, expiry dates, and CI checks keep it under control

Start with one release flag for your next risky feature. Roll it out to your team, then to 5% of users, and watch the error rate. Once the rollout finishes, delete the flag. That full lifecycle, from creation to removal, is the habit that makes feature flags a net win instead of another source of complexity.

For more on related topics, check out our guides on Git workflows and trunk-based development, server-side rendering strategies, and testing strategies for modern web applications.