Experiments

Sampling bias: Types, examples, and how to catch it in experiments

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

A team tests a redesigned search box and gets a clean 50/50 split. Thousands of shoppers convert, no guardrail alarms sound, and the result favors the new box. Days before the broader release, a mobile engineer points out that the experiment ran only on browsers that loaded a particular analytics script. Most shoppers on an older mobile build never appeared in either arm.

The A/B test could still be informative for the people it reached. The problem is the claim the team wants to make about everyone else. Sampling bias occurs when the process that selects or observes units systematically distorts an estimate for the population you care about. In an experiment, ask two separate questions. Does the comparison identify an effect among the participants? And do those participants provide a sound basis for a decision about the future rollout population?

Draw the population boundary before diagnosing the bias

Start with a countable target. “Our users” is too broad to audit. “Distinct signed-in shoppers who start a search on a supported consumer app during the first four weeks of the rollout” tells you where to look for a denominator. It also clarifies which exclusions are intentional. Staff using the internal support console may fall outside the target. Shoppers who temporarily lose connectivity may be central to the target even if they are hard to observe.

Then identify the sampling frame: the source that gives someone a chance to enter the study. In the search example, an event from the analytics script defines a much narrower frame than the application's search-request log. A shopper can appear in the request log without ever contacting the analytics endpoint. Comparing those sources by platform and version gives you a direction for investigation. Check that both systems use compatible identities, dates, environments, and privacy rules before interpreting the difference.

A sample can differ from the target in a visible characteristic without materially biasing a specific effect. For example, older mobile clients may have a lower baseline conversion rate but the same incremental response to the redesigned box. Conversely, a small underrepresented segment could matter greatly if the new implementation fails on that segment's screen size. Bias is about the estimate relative to its target. A demographic mismatch is a clue to investigate, not a complete diagnosis. The distinction between selection and sampling bias helps teams locate the missing step.

Random assignment works after the enrollment boundary

If the assignment system randomizes faithfully among observed shoppers, control and treatment can provide a fair comparison within that frame. It has no power to enroll a shopper whose analytics script never loads. Conversely, you could start with a representative list of all shoppers and still break the treatment comparison by dropping only treatment-side failures from the analysis. Both situations can produce dashboards with large denominators and narrow intervals. They call for different repairs.

Stanford's sampling bias examples illustrate the general problem with drawing a population conclusion from a systematically selected sample. In software, the selection mechanism often takes the form of an SDK requirement, a beta opt-in, a consent setting, a server filter, or a join that requires matching records from two systems. Name the specific mechanism when reporting the risk. “Older Android sessions without a loaded analytics library cannot enter the sample” gives the release owner something they can test.

Size improves precision inside the population you observed

A million desktop shoppers can give you a precise estimate for desktop shoppers under the study design. They do not reveal how an absent mobile client renders the component. If the site records repeated requests instead of distinct eligible people, even the apparent million may have the wrong unit. Start by reconciling people, accounts, sessions, or devices at the level of assignment. Record how much of the target has no chance to appear and what evidence, if any, would let you extend the result.

Follow one sample from recruitment to the final metric

A field-service company wants to change the mobile form technicians use to close a job. The product manager asks whether the new form will help technicians on both iOS and Android submit a complete service record by the end of their shift. The target population is every technician scheduled for a field shift during the coming month. The events already available in the product cover a narrower set at every step.

Coverage starts with who can receive an invitation

In this example, a roster contains 10,000 scheduled technicians. Engineering places the pilot invitation in an Android-only preview channel that can reach 6,000 of them. Every iOS technician has zero chance of entering. That is undercoverage even if everyone who sees the invitation responds. It matters if platform differences change the effect. An offline photo workflow that performs well on the test devices could behave differently on devices outside the pilot.

Measure coverage against the scheduling roster before looking at completion rates. Report the number eligible and reachable by platform, device age, and typical connectivity. A probability sample would give each member of the defined population a known, positive chance of selection. Drawing random invitations from the Android list gives you probabilities within that list. To support the proposed cross-platform decision, the team needs a way to observe iOS technicians or a defensible argument for extending the Android result to them.

Volunteers determine who gets randomized

Of the 6,000 reachable technicians, 1,000 volunteer. A technician who closes 20 jobs a day has a reason to try a faster form. Someone who handles two long repairs each week may skip the invitation. This is self-selection. Compare the volunteers' pre-pilot job volume, connectivity, and tenure with those of reachable nonparticipants. Differences reveal how the pilot population changed. They cause a generalization problem to the extent that the form works differently for those groups.

The team now randomly assigns 500 volunteers to each form. With intact measurement, this supports a causal comparison among participating technicians. Each group contains volunteers subject to the same recruitment process. Random assignment protects the treatment comparison within that group. It gives the other 9,000 technicians no new chance of entering it. That distinction between who enters a study and who receives treatment sits at the center of sampling and selection bias in experiments.

Check who entered the test

Explore practical checks for assignment and measurement before using an experiment to make a release decision.

Read the Experiment Design Lessons

Nonresponse and survivorship change the readout in different ways

Product sends a follow-up satisfaction survey to all 1,000 assigned technicians. Suppose 300 treatment users and 200 control users reply. The survey measures respondents' satisfaction. Perhaps enthusiastic treatment users replied more readily, or frustrated control users sought another way to complain. The counts alone cannot tell you which explanation holds. Nonresponse bias depends on how respondents differ from nonrespondents on the quantity being estimated. Compare response rates across baseline workload and connectivity groups. For a separately sampled follow-up with nonrespondents, use a channel that also reaches technicians who have stopped opening the app.

The behavioral scorecard has a different flaw. It keeps only technicians with a successful end-of-shift sync. If photo upload failures prevent some users of the new form from syncing, the query quietly drops the people most affected by the bug. A team could record faster closeouts among surviving records while leaving more actual jobs unfinished. Survivorship here arises after assignment. Randomizing 500 people per arm at entry cannot protect a comparison subsequently restricted to different kinds of survivors. Telemetry loss in controlled experiments can change estimates as well as reduce the usable sample.

Start from the assignment roster and reconcile expected jobs against the independent dispatch system. A confirmed eligible job with no submission by its deadline is a failure on the defined metric. A device whose submissions cannot be linked has an unknown outcome until the team can reconcile it. Report those counts separately by arm. Inspect post-assignment inclusion rules before deciding which technicians enter the primary comparison. The Android pilot could still support a limited release to similar technicians. The survey and the cross-platform launch each require additional evidence about the people their conclusions would cover.

Trace who disappears between assignment and analysis

An experiment on a mobile payment flow has a surprising result. The new design looks especially strong on Android. Before asking the designer what worked, an analyst compares four populations: eligible accounts, accounts assigned to a variant, accounts whose payment status can be independently observed, and accounts included in the final report. Count distinct accounts at each step using the same enrollment period and a cutoff old enough for every account's outcome window to close.

Suppose an eligibility ledger records 12,000 accounts. Only 10,000 receive an assignment. The remaining 2,000 used a client version that couldn't load either variant. The experiment can still answer a question about supported clients. Describing its result as an estimate for all 12,000 requires an argument about the missing versions and their customers. The assignment query cannot reveal eligible people who never emitted an assignment, so start with a source that exists before enrollment. Use the assignment query's unit and timestamp fields to join the next stage.

Assigned groupAssigned accountsAccounts with observable payment statusAccounts in final report
Control, Android2,5002,4502,450
Treatment, Android2,5002,1002,100
Control, iOS2,5002,4002,400
Treatment, iOS2,5002,4002,400

Assignment is balanced. On Android, status is observable for 98% of control accounts and 84% of treatment accounts. The report includes only those with observable status. If the new payment screen causes customers with interrupted transactions to leave before the client logs a status, the treatment estimate may preferentially describe successful sessions. The table locates the discrepancy. It doesn't tell you what happened in the missing accounts or prove the mechanism.

Inspect the point of loss

Look up a small sample of assigned Android users in the experiment exposure logs or the underlying warehouse records. Check whether each user received the expected variant and whether the payment service recorded a settled, failed, or pending transaction. Distinguish a verified lack of purchase from a missing record in a system unable to observe the purchase. Treating both as zero assigns an outcome to a group whose outcomes you haven't established.

Run a synthetic journey on each client and in each variant. Include a completed payment, a cancellation, a backgrounded app, and a retry after a lost connection. Give the test accounts known identifiers and record when each event should arrive. Compare client logs, the collector, warehouse tables, and the final joined report. Research on telemetry loss in online experiments explains how missing measurements can bias effect estimates. A working synthetic payment narrows an investigation, but a single clean device cannot establish coverage in the customer population.

Understand what the allocation check establishes

A sample ratio mismatch check compares observed assignment counts with their expected split. In this example, the 5,000-to-5,000 assignment counts would give you no warning. Run counts again after each material filter and by pre-assignment characteristics such as device type. A downstream discrepancy should prompt inspection of that step. Filtering on a behavior the treatment legitimately changes, such as successfully reaching a confirmation screen, can also alter proportions. The sample ratio mismatch taxonomy helps distinguish assignment faults from later execution or analysis issues.

If an independent payment ledger covers all assigned accounts, rebuild the outcome from that ledger and rerun the comparison. If some outcomes remain unknowable, report the missing fractions and test how the decision changes under plausible outcomes for those accounts. The CONSORT reporting guideline offers a useful habit from randomized studies: account for participants across assignment, follow-up, and analysis, with reasons for exclusions. Give readers the count at which the sample became narrower and the product decision the surviving evidence can support.

Reweight a result for the audience that will get the release

A pricing-page experiment recruits mostly desktop visitors because its first release runs on a desktop-heavy campaign. Treatment and control were assigned fairly. The team nevertheless has a sampling question. Next month's rollout will include many more mobile customers. A clear result for the pilot audience can still leave the rollout decision uncertain if the effect depends on device.

Start with an independent count of the target audience. Suppose 80% of pilot participants used desktop and 20% used mobile. The upcoming rollout population is 30% desktop and 70% mobile, based on eligible visitors across all planned acquisition channels. Use the device classification at the point of eligibility and the same definition of a visitor in both datasets. If the target distribution instead comes from pageviews, customers who refresh repeatedly can distort the weights before the calculation even begins.

Work in percentage points before combining groups

In this illustrative experiment, desktop conversion moves from 20% in control to 24% in treatment, a gain of 4 percentage points. Mobile conversion moves from 12% to 10%, a loss of 2 points. Given the pilot's device shares, the weighted difference is 0.80 × 4 plus 0.20 × (−2), or +2.8 percentage points. This is the effect on the absolute conversion scale for a population with the pilot composition.

Now apply the target shares to those same within-device differences. At 30% desktop and 70% mobile, the estimated difference is 0.30 × 4 plus 0.70 × (−2), or −0.2 percentage points. The trial data didn't change. The two estimates answer questions about different audiences. If you prefer to check the arithmetic, target-weighted control conversion is 14.4%, and target-weighted treatment conversion is 14.2%. Keep relative lifts separate. Averaging a desktop relative lift and a mobile relative lift with population weights generally won't reproduce the overall relative change.

The sign change suggests a practical investigation. Ask design to inspect the mobile page, and ask the analyst how precisely the pilot estimated the mobile difference. Only one fifth of the pilot supplied mobile observations. Giving that group a 70% weight increases the influence of its noise as well as its estimated effect. Report the uncertainty of the standardized result. The methods for generalizing randomized trial evidence make explicit that the target population and its measured characteristics are part of the analysis.

Identify customers the weights cannot represent

The calculation assumes that eligible mobile users in the pilot are informative about mobile users who will get the release. Suppose the pilot's mobile visitors all came through a returning-customer email, while next month's mobile visitors will be first-time shoppers from search. Device weighting leaves that difference untouched. Tabulate acquisition channel and prior customer status alongside device if they plausibly change the effect. Distinguish a characteristic that merely predicts conversion from one that changes how conversion responds to treatment.

If the target audience includes a mobile client that never entered the pilot, no weight supplies its missing treatment comparison. A large weight on a handful of customers presents a related precision problem. Transporting trial results depends on overlap and defensible assumptions about differences between populations. Sometimes the cheapest reliable answer is to recruit from the missing group or limit the release to the supported audience while gathering more data. Keep the unadjusted pilot estimate alongside the rollout estimate so the decision maker can see exactly which inference requires those assumptions.

Hand the release owner a claim with a boundary

Write down the audience that could enter, how many assigned units remained observable, and who would receive the next rollout. If the experiment identifies an effect for current desktop shoppers, say that directly. Launching on a new mobile surface may require a separate test, improved measurement, or a narrower release while the team learns about the missing population. Never treat an opted-out audience as permission to collect additional identifiable data.

Keep the original counts and rules beside the readout. A future engineer should be able to explain which records were intentionally excluded, which disappeared unexpectedly, and which difference changed the decision. That record prevents a result qualified in the analysis meeting from turning into a claim about every user in the quarterly deck.

Review your metric population

Use the KPI guide to align the metric denominator with the people your product decision will affect.

Read the KPI Playbook

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.