Experiments
Analytics

Pairwise comparison: What it is and when to use it

A graphic of a bar chart with an arrow pointing upward.

Two variants can both beat control without either being proven better than the other.

A team runs four onboarding experiences. Two show encouraging results against the original flow. Someone sorts the point estimates, picks the largest, and calls it the winner. The dashboard looks decisive, but the treatment-versus-treatment question may never have been tested.

Pairwise comparison means comparing two alternatives at a time. It helps answer specific questions about groups, treatments, or options. The method becomes useful when you define the exact contrasts, respect the data's structure, and account for the family of claims you might make.

This guide focuses on statistical comparisons for product teams. It also distinguishes preference ranking, explains why “pairwise” does not mean “paired,” and works through a small multiple-comparison example without pretending that a sorted list of estimates is a reliable ranking.

Define the comparison before choosing the test

State the contrast in practical terms

A contrast is the difference you want to estimate. “Does the shorter onboarding flow improve activation relative to the existing flow?” is specific. “Which experience is best?” needs more definition: best for which metric, population, observation window, and cost?

Write the direction and scale explicitly. A treatment-minus-control difference in activation percentage points is not the same as a relative percentage lift. Positive values also need a clear meaning: an increase is good for activation but may be bad for error rate.

Multiple-comparison analysis starts with these questions because several different contrasts can arise from the same dataset. The data do not determine which claims were intended or which would justify the decision.

Distinguish comparison from preference ranking

In a prioritization meeting, pairwise comparison may mean asking which of two ideas is preferred. That can help make criteria visible and reduce the difficulty of judging a long list all at once.

Those judgments are not automatically causal evidence about product outcomes. A participant can prefer idea A to B, B to C, and C to A. Different audiences can also disagree. A simple win count hides the strength, consistency, and representativeness of those preferences.

If you use preference comparisons, state the criterion, who supplied the judgments, and how ties or disagreement were handled. If the question is whether an implemented change improves activation, collect an appropriate experiment rather than treating an internal ranking exercise as a substitute.

Distinguish pairwise from paired

Pairwise describes two alternatives being compared. Paired describes related measurements: the same users before and after a change, matched units, or the same evaluation queries scored by two models.

A paired-sample test uses the relationship within those pairs. An ordinary randomized A/B test with different users in each arm generally requires an independent-group analysis instead.

Comparing two models on identical offline prompts can create a paired evaluation; randomizing different users to those models online creates a different design. Pairing alone also does not establish causality. A before-and-after comparison can still be affected by time trends or other changes.

Choose the family of contrasts you need

Count all unique pairs

With k alternatives, the number of unique unordered pairs is k(k − 1)/2. Four alternatives produce six comparisons: A–B, A–C, A–D, B–C, B–D, and C–D. Five produce ten, and ten produce 45.

The growth matters operationally. Each new variant adds comparisons, divides available traffic, and creates more opportunities for a favorable-looking result. A large variant set can be expensive even when implementing each additional design is easy.

Design with four alternativesContrastsCount
Every pairA–B, A–C, A–D, B–C, B–D, C–D6
Treatments against control AB–A, C–A, D–A3
One planned contrastD–A1

Reversing A–B to B–A changes the sign of an effect, not the number of unique unordered pairs. If your analysis asks distinct directional questions, however, define those hypotheses and their error handling explicitly rather than assuming this simple count covers every decision rule.

Use control comparisons for replacement decisions

If the decision is whether any new flow improves on the existing one, treatment-versus-control contrasts may be the relevant family. You do not necessarily need every treatment pair to make a defensible replacement decision.

But do not extend the conclusion. If B and D both beat A, the evidence does not automatically establish that D beats B. Their estimated improvements can be close relative to their uncertainty, and the shared control makes the estimates statistically related.

Choose between acceptable variants using the evidence actually collected, practical costs, and your decision policy. If superiority between B and D matters, plan that contrast or run a suitable follow-up. A larger point estimate alone is insufficient.

Decide the scope before inspecting winners

A family is the collection of hypotheses over which you want an error criterion to apply. It may include several variation contrasts on one primary metric, or a larger set of metrics and segments that can generate a success claim.

Selecting the strongest pair after examining all six is not equivalent to having planned only that pair. Nor does hiding five comparisons from the final report eliminate the selection that already occurred.

GrowthBook's multiple-testing documentation explains supported correction methods and scope. Check the actual configured family. A change of reference variation or an exploratory segment view should not silently become evidence for a broader confirmatory ranking.

Plan the claims before comparing

Review how comparison families, statistical power, and repeated checks affect the conclusions you can trust from an experiment program.

Read the Experiment Risks Guide

Match the method to the design and outcome

An omnibus result does not identify a pair

An omnibus one-way ANOVA tests whether group means are all equal under its model. Rejection suggests at least one difference; it does not identify which groups differ or establish a complete ranking.

The ANOVA and pairwise distinction prevents a common reporting leap: a significant overall test is not a license to label the highest observed mean significantly better than every other mean.

There are valid plans with a global test followed by specified comparisons, and valid plans that analyze prespecified contrasts directly. An omnibus test is not a universal prerequisite for every pairwise analysis. Choose a coherent procedure instead of adding an ANOVA mechanically to every product experiment.

Know what Tukey and Dunnett are designed for

Tukey's method addresses all-pair comparisons of means. Classical versions assume independent observations within and across groups, normally distributed within-group outcomes, and a common finite variance. Unequal sample sizes call for the appropriate variant, such as Tukey–Kramer; they are a different issue from unequal variances.

Dunnett's method compares several treatment means against a shared control. Its classical model also assumes independent observations, normal within-group distributions, and a common finite variance. It is designed around that narrower contrast family rather than spending the same effort on every treatment pair.

Neither name is a universal answer for binary conversion, skewed revenue, ratios, repeated observations, or sequential monitoring. Unequal-variance alternatives and other estimators exist. Start with the outcome and design, then choose a method whose validity conditions fit.

Preserve a valid underlying test

A correction works on the evidence produced by the underlying analysis. If repeated request rows are incorrectly treated as independent users, adjusting their p-values does not repair the missing dependence structure.

For each contrast, define the randomized unit, outcome aggregation, observation window, exclusions, and estimator. Use metric definitions that represent the same question across arms. Do not compare one arm's per-session value with another arm's per-user value.

GrowthBook's statistical details describe how its engine estimates effects and uncertainty. The examples here illustrate comparison logic; they do not prescribe a different statistical engine for every GrowthBook metric.

Work through an adjusted comparison family

Start with six clearly labeled hypotheses

Suppose the analysis plan specifies all six pairwise hypotheses for four alternatives on one outcome. To illustrate adjustment, use six hypothetical valid raw p-values: 0.003, 0.008, 0.019, 0.040, 0.200, and 0.600.

These are teaching inputs, not results calculated from an invented experiment dataset. Their purpose is to show why comparing every raw value with 0.05 differs from controlling a family-wise error rate.

Raw testing would reject the first four at 0.05. A family-wise procedure asks a different question: how can the chance of any false rejection in the declared family be controlled under the procedure's assumptions?

Apply Holm's step-down rule

For six tests and a family-wise alpha of 0.05, Holm's rule sorts p-values and compares the smallest with 0.05/6. If it passes, compare the next with 0.05/5, continuing until the first failure. After that failure, do not reject later hypotheses under the procedure.

Sorted raw p-valueHolm comparison thresholdStep-down result
0.0030.00833Reject
0.0080.01000Reject
0.0190.01250Stop; do not reject this or later hypotheses
0.040Not reachedDo not reject
0.200Not reachedDo not reject
0.600Not reachedDo not reject

The corresponding Holm-adjusted p-values are 0.018, 0.040, 0.076, 0.120, 0.400, and 0.600. Compare those adjusted values with the family alpha. Do not also compare them with the already divided thresholds, which would apply another adjustment.

Holm's adjustment controls family-wise error for valid component p-values without requiring independence among them. That matters for shared-control contrasts, which are not unrelated tests. Other procedures target different error criteria and can require different dependence conditions.

Keep the interpretation narrower than a ranking

Rejecting two hypotheses establishes evidence against those two nulls under the analysis plan. It does not create evidence for every untested ordering. Keep the mapping from each p-value back to its contrast, effect estimate, and direction.

Failure to reject a pairwise difference does not establish equality. Two variants may be practically similar, or the comparison may simply lack precision. If practical equivalence matters, define a margin and use an appropriate equivalence analysis.

Nonsignificance is not transitive: A–B and B–C can be nonsignificant while A–C is significant. Do not merge variants into an equivalence group from those labels alone.

Also distinguish per-comparison intervals from simultaneous coverage. A table of ordinary 95% intervals is not automatically a family-wise 95% interval set. Label the method and adjustment so a reader does not infer more protection than the report provides.

Design a comparison plan that supports the release

Plan traffic around the contrasts

More variants do not create more information per variant. With fixed total traffic, splitting across more arms leaves fewer units for each estimate. Additional correction can make small differences harder to detect.

Use power planning for the effect sizes and contrasts that matter. Equal allocation may be reasonable in some designs; a shared-control design can justify different allocation. Do not change allocation opportunistically after looking at promising comparisons without an appropriate adaptive plan.

If the real objective is choosing between two finalists, it may be more useful to test fewer alternatives with sufficient information than to run a broad tournament that cannot distinguish close candidates. Screening and confirmatory stages should have explicit roles and independent evidence where needed.

Record configuration and validity checks

Before launch, list the alternatives, control, primary metric, contrast family, sidedness, correction method, monitoring plan, and practical decision threshold. Use the experiment configuration to implement the intended design and verify it matches the plan.

Check assignment, exposure, identity, and missing outcomes before interpreting pairwise differences. A variant with broken logging can look different from every other arm for reasons unrelated to the customer experience. Family-wise adjustment does not make that comparison causal.

Separate confirmatory contrasts from exploratory findings. A newly discovered segment pattern can motivate another test without becoming a preplanned win retroactively. Record the complete family considered, including unfavorable comparisons, so the final story preserves the selection context.

Report differences people can act on

For each decision-relevant contrast, report its direction, effect scale, estimate, uncertainty method, adjusted evidence where applicable, and sample support. Explain what remains unresolved rather than forcing every variant into a precise rank.

If several variants meet the product's requirements and their differences remain uncertain, maintenance cost, accessibility, operational complexity, or a planned follow-up can guide the next step. State that reasoning directly. Statistical analysis need not invent a sole winner when the evidence does not distinguish one.

GrowthBook's experimentation platform supports the surrounding metric and analysis workflow. A useful comparison plan still begins with your decision: which two alternatives must be distinguished, across which family, and with what evidence before you act?

Compare alternatives that matter

Set up GrowthBook with your metrics, then define the alternatives, comparison scope, and decision criteria for your next product experiment.

Get Started With a Test Plan

FAQs

A pairwise comparison evaluates two alternatives at a time. In statistical analysis, it usually estimates or tests a contrast between two groups; it does not by itself specify the data design or testing method.

For k alternatives, multiply k by (k minus 1), then divide by 2 to count unique unordered pairs. Comparing every treatment only with one shared control instead produces k minus 1 comparisons.

No. Pairwise describes which two alternatives are compared, while paired describes related observations such as two measurements on the same unit. Independent A/B arms can be compared pairwise without being paired data.

No. A treatment-versus-control result addresses that contrast only. To support a treatment-versus-treatment claim, evaluate that contrast with the intended effect definition and appropriate uncertainty and multiplicity handling.

GrowthBook offers supported correction methods for specified experiment metrics and variation comparisons. Review its multiple-testing documentation and verify the configured scope rather than assuming every dashboard view is an adjusted all-pairs ranking.

Table of Contents

Related Articles

See All Articles
Feature Flags
Experiments

Add local feature flags to a React app with TypeScript

Nov 20, 2026
x
min read

A magazine's home page shows two recent issues. The design team wants subscribers to try a shelf with four. All four covers are public, and changing editions while the page is open should update the shelf immediately. That gives you a small React feature with a useful acceptance test. Click from guest to subscriber and back, and count the covers each time.

We'll put the display limit in a typed local flag, evaluate it inside a React component, and leave the choice of edition with the app. The example runs in a client-rendered React app without a GrowthBook account, an SDK key, or a request for flag rules. For the wider workflow, free feature flags for coding agents explains what to ask an agent to implement and how to review the result.

Define what one flag controls

Start with an existing React and TypeScript app, or create a Vite React project for the example. Install both GrowthBook packages so the definitions and the hooks resolve against compatible SDK versions.

npm create vite@latest issue-shelf -- --template react-ts
cd issue-shelf
npm install
npm install @growthbook/growthbook@^2.2.0 @growthbook/growthbook-react@^2.2.0

Create src/flags.ts. Here the feature value is a number, which lets the component use the same rendering code for either edition. A future change from four covers to three is one edit to the rule.

import type { LocalFeatures } from "@growthbook/growthbook";

export type Edition = "guest" | "subscriber";
type Features = { issueLimit: number };
type Attributes = { id: string; edition: Edition };

declare module "@growthbook/growthbook" {
  interface Register {
    features: Features;
    attributes: Attributes;
  }
}

export const features: LocalFeatures = {
  issueLimit: {
    defaultValue: 2,
    rules: [
      { condition: { edition: "subscriber" }, force: 4 },
    ],
  },
};

A guest falls through to the default of two. A subscriber matches the rule and gets four. This rule applies to every subscriber, so the ID has no effect on the result here. If you later roll the shelf out to a percentage of subscribers, you already have an identity to use for repeatable assignment.

The type registration release note explains the version requirement for LocalFeatures. The registration connects the definition, the attributes, and the value returned by the hook. For the TypeScript mechanics, see Jeremy Dorn's Register pattern walkthrough.

Put the current reader above the shelf

Replace src/App.tsx with the component below. The edition switch is a local fixture so anyone reviewing the change can reproduce both states. In an existing app, take those two values from the active reader in your session layer.

import { useMemo, useState } from "react";
import { GrowthBook, GrowthBookProvider } from "@growthbook/growthbook-react";
import { features, type Edition } from "./flags";
import { IssueShelf } from "./IssueShelf";

export default function App() {
  const readerId = "reader-17";
  const [edition, setEdition] = useState<Edition>("guest");

  const gb = useMemo(() => new GrowthBook({
    attributes: { id: readerId, edition },
    defaultHashVersion: 2,
  }).initSync({ payload: { features } }), [readerId, edition]);

  return (
    <GrowthBookProvider growthbook={gb}>
      <main>
        <h1>Recent issues</h1>
        <p>Current edition: {edition}</p>
        <button onClick={() => setEdition(
          edition === "guest" ? "subscriber" : "guest"
        )}>
          Switch edition
        </button>
        <IssueShelf />
      </main>
    </GrowthBookProvider>
  );
}

The provider receives an instance initialized with the current reader and the checked-in rules. React can render the correct shelf on the first pass for that reader. If the app is still loading a session, decide what should occupy the shelf in the meantime. For this public list a two-cover guest view is reasonable. On a page where a switch would interrupt the reader, wait for the session before mounting the shelf.

Give your agent the React setup

Use the local flags guide to ask for a typed definition, a provider with the current reader, and a test that changes the edition.

Open the Agent Guide

The useMemo dependencies include the ID and the edition. If a reader subscribes while signed in, their ID can stay the same while their edition changes. Depending only on the ID would leave the old SDK instance in place. Passing a fresh object as the dependency on every render would create unnecessary instances. The example uses the two primitive values the rule setup actually needs.

Read the numeric flag where React renders the list

Create src/IssueShelf.tsx. Keep one stable ID per issue and let the component use the resolved value to select how many items to render.

import { useFeatureValue } from "@growthbook/growthbook-react";

const issues = [
  { id: "nov", title: "November · Print shops" },
  { id: "oct", title: "October · Bookbinders" },
  { id: "sep", title: "September · Type designers" },
  { id: "aug", title: "August · Paper mills" },
];

export function IssueShelf() {
  const limit = useFeatureValue("issueLimit", 2);

  return (
    <ul aria-label="Recent magazine issues">
      {issues.slice(0, limit).map(issue => (
        <li key={issue.id}>{issue.title}</li>
      ))}
    </ul>
  );
}

Keep the hook at the top of the component, inside the provider's subtree. The React SDK supplies the flag value through that provider. Calling a hook inside a click handler or inside the list loop would break the Rules of Hooks. Use the returned number in ordinary render logic.

There are two places you can see the number two in this implementation. The definition's defaultValue is what an ordinary guest gets through evaluation. The 2 passed to the hook is a fallback for a value the SDK can't supply. Giving them the same value makes the basic shelf a sensible fallback, but checking only the guest case would let a broken provider arrangement or missing definition go unnoticed. The subscriber case proves that the component actually received the rule.

The list keys identify magazine issues. Keep those keys independent of the flag. Switching from two covers to four should preserve the identity of the first two rows. There's also no need to remount the whole app with an edition-specific key. React preserves state according to component position and keys. For example, a search input outside the shelf shouldn't lose its text because someone subscribed.

Check the transition in both directions

Use the template's build script to type-check and bundle the app. Once that passes, start the dev server and open the local address it prints.

npm run build
npm run dev

On first load, the page says guest and lists November and October. Click Switch edition. The same page should say subscriber and add September and August. Click again. The list should return to the original two issues, in order. This last check catches code that appends more results on upgrade and never removes them on downgrade.

For a compile-time check, temporarily replace the numeric fallback with the string "2". Run the build again and inspect the error on the hook call. Then restore 2 and rebuild. If the string compiles, check that src/flags.ts belongs to the same TypeScript project as the component and that the package manager resolved compatible core and React versions.

npm ls @growthbook/growthbook @growthbook/growthbook-react

Look for the core package used by your app and by the wrapper. If the app has several incompatible installations, align the versions before diagnosing the JSX. A team using an existing build script should also confirm it actually runs the TypeScript checker.

Hand off a React change someone can review

Give your coding agent the one-shot local feature flags guide and a short description of the observable behavior. For this shelf, the request can be as specific as the test.

Show two public issues to guests and four to subscribers.
Keep the same reader ID when switching editions in the test.
Report the initial titles, the titles after upgrading, and the titles
after switching back. Include the type-check command you ran.

The shelf controls how many public titles to display. If your actual feature unlocks paid articles, enforce access when the server serves an article. A client-rendered flag only decides what to show in that browser. Whenever a change to the display limit can wait for a deployment, the small local file keeps the decision reviewable alongside the component. When an editor needs to change it between issues without an engineering release, compare the free GrowthBook options for managing flag rules.

Manage the shelf in GrowthBook

Start a GrowthBook workspace when your magazine team is ready to manage shelf rules between deployments.

Get Started with GrowthBook
Feature Flags
Experiments

Use local feature flags per request in Node.js

Nov 20, 2026
x
min read

Two customers download the same weekly report. One has agreed to preview a new CSV column. The other feeds the old two-column format into an importer. Both requests can land on the same Node.js process, and each needs the right file even if the other request arrives while the report is loading.

This tutorial builds that endpoint with one checked-in feature flag. The process loads the rules once. Each request supplies its own workspace attributes and receives its own evaluation. You can run the whole example on your machine without an account, a client key, or a flag server. The free feature flags for coding agents walkthrough introduces the local approach. Here we'll give the agent a server-specific test to pass.

Set up a small TypeScript service

Use Node.js 22 or newer for this example. In an empty directory, create an npm project that uses ES modules, install the core SDK, and add the TypeScript tools.

npm init -y
npm pkg set type=module
npm install @growthbook/growthbook@^2.2.0
npm install -D typescript tsx @types/node@22

Create tsconfig.json at the project root. The sample runs TypeScript directly with tsx and checks types in a separate step. Type checking with tsx explains why the two commands serve different purposes.

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "strict": true,
    "noEmit": true,
    "skipLibCheck": true,
    "types": ["node"]
  },
  "include": ["*.ts"]
}

The following files all live next to that configuration. The server imports ./flags.js even though the source file is flags.ts. That spelling follows TypeScript's Node.js module resolution for ESM and works with this runner.

Define the report contract in one flag

Create flags.ts. The public format has two columns. The sample preview workspace gets one additional column. The only targeting attribute the rule needs today is reportPreview. Carry the workspace ID too, so two people downloading a report on behalf of the same workspace can share an assignment if you introduce a percentage rollout later.

import type { LocalFeatures } from "@growthbook/growthbook";

type Features = { includeUniqueReaders: boolean };
export type Workspace = { workspaceId: string; reportPreview: boolean };

declare module "@growthbook/growthbook" {
  interface Register {
    features: Features;
    attributes: Workspace;
  }
}

export const features: LocalFeatures = {
  includeUniqueReaders: {
    defaultValue: false,
    rules: [{ condition: { reportPreview: true }, force: true }],
  },
};

The SDK type registration update covers this rule syntax and the 2.2.0 minimum. If you misspell reportPreview in a condition or use a string where the boolean flag expects a value, TypeScript can point at the definition. The Register pattern also makes the same feature name available in other modules without threading a generic type through each handler.

Before you add the endpoint, decide what belongs to the process and what belongs to the request. The feature definitions are identical for both customers. Their identity and preview enrollment can differ. If a handler changes an attribute on a single shared user instance before awaiting a database query, another handler could replace that attribute before the first handler resumes.

Give your agent a server-side task

Use the one-shot guide to add checked-in rules. Ask your agent to keep workspace attributes local to each request and demonstrate both CSV formats.

Open the Local Flags Guide

Create a scope when the request arrives

Create server.ts. The Node.js SDK provides GrowthBookClient for the process and createScopedInstance for the current request. The two fixture paths below stand in for two authenticated workspaces. The server binds to the loopback address so you can exercise it locally.

import { createServer } from "node:http";
import { setTimeout as delay } from "node:timers/promises";
import { GrowthBookClient } from "@growthbook/growthbook";
import { features, type Workspace } from "./flags.js";

const client = new GrowthBookClient({ defaultHashVersion: 2 })
  .initSync({ payload: { features } });

const demos = new Map<string, Workspace>([
  ["/demo/preview", { workspaceId: "press-a", reportPreview: true }],
  ["/demo/standard", { workspaceId: "press-b", reportPreview: false }],
]);

createServer(async (req, res) => {
  const workspace = demos.get(req.url ?? "");
  if (req.method !== "GET" || !workspace) {
    res.writeHead(404).end();
    return;
  }

  const gb = client.createScopedInstance({ attributes: workspace });
  await delay(10); // Stand-in for loading this workspace's report.
  const expanded = gb.isOn("includeUniqueReaders");
  const csv = expanded
    ? "period,downloads,unique_readers\nweek-1,80,55\n"
    : "period,downloads\nweek-1,80\n";

  res.writeHead(200, {
    "Content-Type": "text/csv; charset=utf-8",
    "Cache-Control": "private, no-store",
  });
  res.end(csv);
}).listen(4178, "127.0.0.1", () => {
  console.log("Report server listening on http://127.0.0.1:4178");
});

The HTTP handler looks up a workspace, creates its scope, and holds that scope across an asynchronous operation. The short promise-based timer gives a second request time to arrive. In a real export, that's where the database or storage read would happen. Keep the stable client at module scope and the scoped instance inside the handler. If a formatter needs the decision, pass it the boolean or the scoped instance.

In production, resolve the workspace and its access rights from the authenticated session before reading the report. The two selectable paths here are fixtures for public sample data. A caller's choice of a header, query string, or workspace slug can't establish permission to read another customer's report. The endpoint also prevents shared response caching. If you cache real exports, the cache needs to distinguish the workspace and the report format, along with any other inputs that change the response.

Test two requests that overlap

In the first terminal, type-check the service and start it. A successful type check exits quietly. The next command prints the loopback address and keeps the server running.

npx tsc --noEmit
npx tsx server.ts

Save the following as verify.mjs. In a second terminal, run node verify.mjs. Node's built-in fetch calls the local server. Strict assertions compare the full header and data row, including where each row ends.

import assert from "node:assert/strict";

async function report(name) {
  const response = await fetch("http://127.0.0.1:4178/demo/" + name);
  assert.equal(response.status, 200);
  return response.text();
}

const [preview, standard, previewAgain] = await Promise.all([
  report("preview"), report("standard"), report("preview"),
]);

assert.equal(preview, "period,downloads,unique_readers\nweek-1,80,55\n");
assert.equal(standard, "period,downloads\nweek-1,80\n");
assert.equal(previewAgain, preview);
console.log("Both workspaces received the expected CSV.");

You should see the single success line. Testing just the preview workspace proves that the code can add a column. Testing both responses catches the more expensive mistake of silently changing an existing customer's export. Keeping the old format assertion around is especially valuable when the downstream importer belongs to someone outside your team.

To check the compile-time boundary, temporarily change gb.isOn("includeUniqueReaders") to gb.isOn("includeUniqueReader") and rerun npx tsc --noEmit. The diagnostic should identify the misspelled key. Restore it before running the server again. A coding agent can include the before-and-after type check and the two CSV headers in its pull request.

Decide when to expand the report

When one preview customer is ready, leave everyone else on the default. If the next step is to enroll a fraction of workspaces, choose an attribute that matches the promise you're making. Hashing a workspace ID lets colleagues downloading the same report share a format. Hashing each user's ID could give two analysts in the same company different column sets. The one-shot guide shows how to express a percentage and hash attribute in a local rule.

A new rule in flags.ts reaches a process through your deployment. During a rolling deploy, the same workspace might hit old and new processes. If customers need a durable choice of export schema, keep supporting the agreed format in the API itself. When the operational requirement is to change targeting between deploys, you can keep the scoped evaluation in the handler and change how the process receives its rules. The free GrowthBook offerings overview covers Cloud Starter and self-hosting for teams that want to manage those rules.

Manage report targeting in Cloud

Create a GrowthBook workspace when the team supporting exports needs to expand the preview independently of a server release.

Get Started with GrowthBook
Feature Flags
Experiments

Use local feature flags in the Next.js App Router

Nov 20, 2026
x
min read

Your conference agenda has a new “Show room” button. Reviewers should see it on the first page load. Everyone else should get the existing agenda. If a Server Component renders the old agenda and a browser hook independently decides to show the new button, the first HTML and the browser can disagree.

In the Next.js App Router, the server can make this decision once and pass a boolean to the interactive component. We'll define the flag in the repo, select the preview audience with a local test cookie, and verify the actual HTML for both visitors. Clicking the button will still work after hydration. You can follow along without a GrowthBook account or client key. If you're assigning this work to an agent, the free feature flags for coding agents walkthrough gives the background.

Keep the flag definitions on the server

Use a TypeScript App Router project, or create a small one with create-next-app. These paths assume the project has an app directory at its root. If yours uses src/app, put both app and lib under src so the relative imports still match.

npx create-next-app@latest agenda-flags --ts --app --empty --use-npm --no-src-dir --no-tailwind --yes
cd agenda-flags
npm install @growthbook/growthbook@^2.2.0 server-only

Keep the starter's root layout. Create lib/agenda-flags.ts with the following code. The SDK type registration update explains how LocalFeatures checks the flag and its rule against the registered types. This setup requires version 2.2.0 or later.

import "server-only";
import { GrowthBookClient, type LocalFeatures } from "@growthbook/growthbook";

type Features = { agendaRoomDetails: boolean };
type Attributes = { audience: "preview" | "public" };

declare module "@growthbook/growthbook" {
  interface Register {
    features: Features;
    attributes: Attributes;
  }
}

const features: LocalFeatures = {
  agendaRoomDetails: {
    defaultValue: false,
    rules: [{ condition: { audience: "preview" }, force: true }],
  },
};

const client = new GrowthBookClient({ defaultHashVersion: 2 })
  .initSync({ payload: { features } });

export function showRoomDetails(audience: Attributes["audience"]) {
  const gb = client.createScopedInstance({ attributes: { audience } });
  return gb.isOn("agendaRoomDetails");
}

The module can reuse the client and rules across requests handled by the same process. It only holds the current visitor's audience inside the function call. Two requests can therefore use the same flag file and get different results. The Node.js SDK documents the scoped client used under the App Router here.

This particular rule has no percentage and needs no visitor ID. The two audiences are sufficient. If the team later asks for a rollout to 10% of attendees, add a stable attendee or registration ID and choose which of those units should stay together. Jeremy Dorn's Register pattern article explains how a change to an attribute type reaches the call sites that construct it.

Read the cookie for this request

Create app/agenda/page.tsx. The static heading can render for everyone. The request-specific content sits behind a Suspense boundary, so the fallback can show a neutral loading message until the server has the cookie.

import { Suspense } from "react";
import { cookies } from "next/headers";
import { showRoomDetails } from "../../lib/agenda-flags";
import { Agenda } from "./Agenda";

async function AgendaForVisitor() {
  const jar = await cookies();
  const audience = jar.get("agenda-preview")?.value === "1"
    ? "preview"
    : "public";

  return <Agenda showRoom={showRoomDetails(audience)} />;
}

export default function AgendaPage() {
  return (
    <main>
      <h1>Conference agenda</h1>
      <Suspense fallback={<p>Loading the agenda…</p>}>
        <AgendaForVisitor />
      </Suspense>
    </main>
  );
}

The App Router's cookies function reads the incoming request asynchronously. Read it inside the visitor-specific component. Keeping that read out of shared cached code lets the surrounding page reuse common content without treating one visitor's decision as another's. This placement also accommodates App Router projects using Cache Components.

Give your agent the Next.js setup

Use the local flags guide with a concrete request to evaluate one flag on the server and return the same decision to the browser.

Open the Local Flags Guide

The cookie in this demo is a convenient way to preview a public UI treatment. Anyone with that cookie can see the room label. To target paying attendees or private sessions, obtain the audience from the verified session on the server and authorize the underlying data separately.

Pass one decision to the interactive component

Create app/agenda/Agenda.tsx. It's a Client Component because a visitor can open and close the room details. Its initial branch comes directly from the boolean supplied by the page.

"use client";

import { useState } from "react";

export function Agenda({ showRoom }: { showRoom: boolean }) {
  const [open, setOpen] = useState(false);

  return (
    <section data-agenda={showRoom ? "preview" : "standard"}>
      <h2>10:00 · Designing for print</h2>
      {showRoom && (
        <>
          <button aria-expanded={open} onClick={() => setOpen(!open)}>
            {open ? "Hide room" : "Show room"}
          </button>
          {open && <p>Room 204</p>}
        </>
      )}
    </section>
  );
}

The client boundary takes a serializable prop. The component receives true or false. The SDK instance, targeting rules, and cookie handling stay in the server module. You don't need a React provider for this component because its only browser-side choice is whether the visitor has clicked the button.

Follow one page load through server rendering and hydration. For a preview visitor, the server can send a section with a “Show room” button. React's first client render gets the same showRoom value and starts with open set to false. Hydration attaches the click handler. Opening the room detail then updates component state and doesn't require another flag evaluation.

Verify the HTML and the click separately

Build the production app and start it on port 3100.

npm run build
npm run start -- -p 3100

In a second terminal, save this as verify-agenda.mjs in the project root and run node verify-agenda.mjs. The test makes two requests to the same route and looks for a marker on the rendered section. A marker in the HTML helps catch an implementation that only adds the intended layout after JavaScript runs.

import assert from "node:assert/strict";

async function agenda(cookie) {
  const response = await fetch("http://localhost:3100/agenda", {
    headers: cookie ? { Cookie: cookie } : {},
  });
  assert.equal(response.status, 200);
  return response.text();
}

const [standard, preview] = await Promise.all([
  agenda(""), agenda("agenda-preview=1"),
]);
assert.match(standard, /<section data-agenda="standard"/);
assert.doesNotMatch(standard, /<section data-agenda="preview"/);
assert.match(preview, /<section data-agenda="preview"/);
assert.doesNotMatch(preview, /<section data-agenda="standard"/);
console.log("Both agenda layouts arrived in the server HTML.");

Now open http://localhost:3100/agenda in a fresh browser profile. You should see the session title without a room button. In that local page's browser console, set the demo cookie and reload.

document.cookie = "agenda-preview=1; Path=/; SameSite=Lax";
location.reload();

Click Show room and look for Room 204. Click Hide room and the room should disappear. This second check proves the component became interactive. If the server response test passes but the click fails, inspect the browser console for a hydration error before changing the flag rules.

Remove the fixture and reload once more. The button should disappear and the agenda title should remain.

document.cookie = "agenda-preview=; Path=/; Max-Age=0";
location.reload();

The reload is deliberate. Editing the cookie in an already open document doesn't rerun its Server Component. In your app, use the normal session-change flow to request a fresh server render when a visitor signs in, signs out, or leaves a preview group.

Choose where the next flag should be evaluated

For a decision needed in the initial HTML, give the agent an observable requirement. Ask it to show the two HTTP responses, then click the interactive control in the preview. The first check catches an incorrect layout. The second catches correct HTML that never becomes interactive.

If a later feature depends on an action entirely within the browser, evaluate whether its flag belongs in the client tree. The one-shot local flags guide covers both placements. This agenda only needs one server decision. Updating its checked-in rule takes a deployment. Keep that tradeoff in view if the event organizer needs to pause a preview while attendees are already arriving. For that case, compare GrowthBook’s free options for changing flags between deploys.

Manage the agenda rollout in Cloud

Create a GrowthBook workspace when the organizer needs to adjust a preview audience while your Next.js app is serving attendees.

Get Started with GrowthBook

Ready to ship faster?

No credit card required. Start with feature flags, experimentation, and product analytics—free.

Simplified white illustration of a right angle ruler or carpenter's square tool.White checkmark symbol with a scattered pixelated effect around its edges on a transparent background.