Matched pairs experiment: definition and examples

Most failed experiments don't fail because the treatment didn't work.
They fail because the groups being compared were never truly comparable to begin with. A matched pairs experiment is one of the most direct ways to fix that problem — not by collecting more data, but by structuring the experiment so that the most dangerous sources of noise are removed before a single data point is collected.
This guide is for engineers, PMs, and data practitioners who run experiments and want cleaner results without inflating sample sizes. Whether you're designing a clinical study, a behavioral research task, or an A/B test on a niche user segment, the same core principle applies: pair subjects on the variables most likely to distort your results, then randomize within those pairs. Here's what you'll find in this article:
- What a matched pairs experiment actually is — the structure, the two design variants, and how it differs from standard randomized designs
- Why it reduces noise — the role of confounding variables and the statistical mechanism that makes matching work
- Real examples across domains — from psychology labs and clinical trials to product teams at Khan Academy and Floward
- Honest tradeoffs — where the design earns its complexity and where simpler approaches will serve you better
- How to analyze the data correctly — the paired t-test, when to use alternatives like the Wilcoxon or McNemar test, and why using the wrong test quietly discards the precision you worked to build
The article moves from concept to mechanics to real-world application, so you can read straight through or jump to the section most relevant to where you are in your experiment design process.
Matched pairs experiments force balance before randomization begins
A matched pairs experiment is a controlled experimental design in which participants are grouped into pairs based on shared characteristics before any treatment is assigned. As Li, Dasarathy, and Berisha describe it, the design "groups participants with similar properties into pairs, randomly assigning the treatment to one participant in each pair and the control to the other."
The result is a structure where treatment effects can be evaluated by comparing outcomes within pairs rather than across two loosely assembled groups — a subtle but consequential distinction that shapes everything from how you recruit participants to how you analyze results.
Matching first, randomizing second
The core logic of a matched pairs experiment unfolds in two steps: first match, then randomize. Matching happens before any treatment is applied. Once pairs are formed, randomization determines which member of each pair receives the treatment and which serves as the control. This means matched pairs design is not a replacement for randomization — it is a constraint on it.
Random assignment still occurs, but it operates within a structure that has already neutralized the most dangerous sources of between-subject noise. The design is a specific subtype of controlled experiment, and its defining feature is that balance on key variables is guaranteed by construction rather than left to the probabilities of chance.
Matching variables are a design decision, not a default
Pairs are constructed by identifying variables most likely to influence the outcome — the confounders — and finding two subjects who are closely similar on those dimensions. In behavioral research, researchers commonly match on characteristics like age, IQ, or prior task performance. In clinical settings, baseline health status or disease severity might be the matching criteria. In digital product experimentation, teams might pair users based on past engagement levels, account tenure, or historical conversion behavior before assigning them to a new feature or onboarding flow.
The choice of matching variables is a deliberate design decision, not an arbitrary one. The variables you match on should be the ones you have strong reason to believe will correlate with your outcome measure. Matching on irrelevant variables wastes effort and can actually reduce statistical efficiency. Matching on the right variables is what gives the design its power.
The two structural variants
Matched pairs experiments take two distinct structural forms. In the first, two different subjects are matched on shared characteristics and then separated — one goes to the treatment condition, one to the control. This is the form most commonly described in the experimental design literature, and it applies naturally to situations where the same person cannot logically receive both conditions simultaneously.
In the second form, a single subject is exposed to both conditions in sequence, effectively serving as their own matched pair. This within-subject or repeated measures variant is the most extreme version of matching because every individual-level characteristic — genetics, baseline ability, personality — is held constant across both conditions.
The statistical efficiency gains are substantial. The practical risk is carryover: the first condition may influence the subject's response to the second, contaminating the comparison. Whether this tradeoff is acceptable depends on the nature of the treatment and the outcome being measured.
How matched pairs differs from fully randomized designs
In a fully randomized design, participants are assigned to treatment or control purely by chance, with no pre-matching. Group balance on key variables is probabilistic — likely at large sample sizes, but not guaranteed. At small sample sizes, random assignment alone can produce groups that differ meaningfully on variables that matter, and those differences will bias your treatment effect estimate.
Matched pairs design addresses this directly. Because pairs are formed before randomization, the groups are balanced on matched variables by construction. The arXiv paper frames this benefit in terms of variance reduction: the design "decreases the sample size required for valid conclusions" precisely because it removes the between-subject noise that a fully randomized design leaves uncontrolled.
This is why the design appears across domains as different as clinical trials, policy evaluation, and website experimentation — anywhere the cost of participants is high and the margin for imbalanced groups is low, the matched pairs structure earns its complexity.
Why matched pairs designs reduce noise: the role of confounding variables
If you've ever run an A/B test where the results seemed implausibly strong — or suspiciously weak — confounding variables are often the culprit. They operate quietly enough that standard diagnostic checks won't always catch them. Matched pairs designs exist specifically to neutralize this threat at the design stage, before data collection begins. Understanding why they work requires understanding what confounders actually do to your estimates.
Confounders corrupt treatment effect estimates before data collection begins
A confounding variable is any variable that correlates with both how participants are assigned to treatment and what outcome they produce. When that kind of variable is unevenly distributed across your experimental groups, it distorts your treatment effect estimate — making an intervention look better or worse than it actually is.
The classic product experimentation version of this problem: suppose you're testing a redesigned onboarding flow, and your test group happens to contain a higher proportion of tech-savvy users than your control group. Your new design appears to lift activation rates, but the difference is largely attributable to who saw what, not what they saw.
The user composition did the work, not the design. This is confounding in practice, and it's common enough that even well-intentioned randomization can produce it — particularly when sample sizes are small and the law of large numbers hasn't had room to operate.
GrowthBook's own experimentation documentation flags a related version of this problem: filtering users based on post-assignment activity that differs across variations can introduce bias that standard sample ratio mismatch checks won't detect. Matched pairs designs address this class of problem at the source, before any filtering decisions arise.
The statistical mechanism: removing between-subject variance
The reason matching works isn't intuitive at first, but the logic is clean once you trace it through. When you pair participants on a variable — say, prior engagement level or age — that variable's contribution to outcome variance gets removed from the error term in your analysis. It no longer shows up as noise in your estimate of the treatment effect.
The consequence is direct: residual error variance drops, which shrinks the standard error of your treatment effect estimate, which increases statistical power for a given sample size. You're not collecting more data; you're extracting more signal from the data you have. You're forcing balance on the variables most likely to obscure the true effect, rather than hoping randomization distributes them evenly by chance.
This is the same underlying principle behind variance reduction techniques like CUPED and post-stratification, which modern experimentation platforms implement as part of their core statistical infrastructure. The difference is timing: matched pairs achieves covariate control at the design stage, while CUPED applies it analytically after the fact. Teams that can't implement matched pairs at the design level can often recover similar power gains through these post-hoc approaches.
Matching pays off only when the right variables are known in advance
Matched pairs designs earn their complexity when three conditions hold simultaneously: sample sizes are small, the variables you're matching on are strong predictors of the outcome, and those variables are measurable before treatment assignment begins.
When sample sizes are large, randomization alone tends to produce balanced groups, and the overhead of constructing matched pairs may not be worth the marginal power gain. But in smaller experiments — a clinical trial with 40 participants, a product test on a niche user segment — random assignment can easily produce groups that differ meaningfully on variables you care about. Matching closes that gap by design.
The catch is that you have to know which variables to match on before you start. Identifying which variables actually matter can feel like playing whack-a-mole. Matching on variables that don't predict the outcome doesn't reduce noise — it just consumes degrees of freedom and complicates your analysis without payoff. The design rewards researchers who have enough domain knowledge to identify the right covariates in advance, and it penalizes those who guess.
Matched pairs experiment examples across research and product contexts
The conditions that make matched pairs design work — small samples, known confounders, measurable before assignment — appear across research domains that otherwise have little in common. The matched pairs design is not the property of any single discipline.
Whether you're running a cognitive psychology study, enrolling patients in a clinical trial, or testing a new onboarding flow with millions of users, the underlying logic is identical: identify the variables most likely to distort your results, pair subjects on those variables, and then randomize within pairs. What changes across domains is which variables matter. What stays constant is why matching matters at all.
Psychology and behavioral research: matching on individual characteristics
In behavioral research, the primary threat to clean causal inference is individual variation — differences in cognitive ability, prior knowledge, or baseline performance that have nothing to do with the treatment being tested. A classic matched pairs setup addresses this directly. Before assigning participants to experimental and control conditions, a researcher pairs them on variables like IQ, age, or prior test scores. Each pair is then split: one person goes to the treatment group, the other to the control. The result is something like having a twin study without needing actual twins.
The value here is that any difference in outcomes between the two groups is far less likely to be explained by pre-existing cognitive differences, because those differences were deliberately balanced out before the experiment began. If you skip this step and rely on pure randomization with a small sample, you might end up with a treatment group that is systematically sharper or more experienced than your control — and your effect estimate will be wrong in ways that are hard to detect after the fact.
Clinical trials: matching when participant pools are small
Clinical research faces a compounding version of this problem. Not only are individual differences a confounding threat, but patient recruitment is expensive and slow, which means sample sizes are often too small for randomization alone to guarantee balanced groups. Matching on patient characteristics — age, disease severity, baseline biomarker levels — before assigning treatment versus placebo is a practical response to this constraint.
The logic is the same as in psychology: a treatment group that happens to be younger or healthier than the control will produce inflated efficacy estimates, not because the treatment works better, but because the groups were never comparable to begin with. Matching forces that comparability before the trial begins, which means the resulting treatment effect estimate is doing less work to account for pre-existing differences and more work to reflect what the intervention actually caused.
Digital product and A/B testing: matching on behavioral attributes
Product experimentation teams encounter the same confounding problem at a different scale. If your test group happens to have more tech-savvy users than your control, you'll think your new design is amazing when really you just got lucky with who saw what. The solution is to match users on behavioral attributes — past engagement, session frequency, account age, or product sophistication — before assigning them to a new feature or onboarding flow.
Khan Academy applies this logic in practice. Rather than rolling out experiments by simple percentage splits, their team uses classroom and district tags to control targeting before measuring learning outcomes. As John Resig, Khan Academy's Chief Software Architect, put it: "Having tags for the classroom or the district a student is in, and then actually rolling out based on those, gives us a lot more power." That's the matched pairs principle applied to an EdTech product context — control for educational environment first, then measure the treatment effect.
Floward, an e-commerce platform operating across heterogeneous markets, takes a similar approach by segmenting experiments on country, language, and device type before running localized tests. Their homepage experiment comparing Saudi Arabia and Kuwait audiences reached statistical significance in under two weeks — a result tied directly to the fact that they controlled for market-level variation before measuring treatment effects, rather than pooling across incomparable user populations.
The same confounding problem appears in every domain — only the variables change
Strip away the domain-specific details and the same principle emerges every time: uncontrolled variation on variables that predict your outcome will corrupt your treatment effect estimate. Matching is the mechanism for removing that variation before it can do damage.
The Berkeley admissions data from 1973 — where aggregate admission rates appeared to favor men, but department-level analysis reversed the finding entirely — is a well-documented illustration of what happens when confounders go uncontrolled. The confounding variable (which departments applicants chose) produced an aggregate result that was directionally wrong.
Whether the matching variable is IQ, disease severity, or past user engagement, the researcher's job is the same: identify what matters, pair on it, and then let randomization do the rest within pairs.
Matched pairs design delivers power gains with specific tradeoffs
Matched pairs experiments are genuinely powerful — but they're not universally the right choice. Understanding both what the design delivers and where it breaks down is what separates researchers who use it well from those who apply it reflexively or avoid it out of misplaced caution.
The design's statistical advantages are real but conditional
The core statistical advantage is straightforward: by pairing participants on variables most likely to distort your results before randomizing treatment assignment, you remove a meaningful chunk of variance from the error term. That tighter error variance translates directly into increased statistical power — meaning you can detect real effects with smaller samples than a fully randomized design would require. For teams running experiments where recruiting participants is expensive or slow, this efficiency matters.
Beyond power, matched pairs designs offer several practical benefits that are easy to overlook. Because two different participants are assigned to each condition rather than the same participant experiencing both, there are no order effects or carryover effects to worry about. A participant in the control condition hasn't already been primed by the treatment.
You can also use identical test materials across conditions without concern about practice effects, since no participant sees both versions. And because participants only encounter one condition, they're less likely to guess the study's purpose and adjust their behavior accordingly — reducing the risk of demand characteristics contaminating your results.
Taken together, these advantages make matched pairs designs particularly well-suited to contexts where individual differences are large relative to the expected treatment effect, sample sizes are constrained, and you have enough prior knowledge about your population to identify meaningful matching variables.
The matching difficulty problem
The central practical limitation is that finding well-matched pairs is hard, and it gets harder fast. Matching on one variable — say, age — is manageable. Matching on age, prior engagement, device type, and account tenure simultaneously requires a much larger pool of candidates to find adequate pairs. The more matching variables you add, the exponentially smaller the subset of your population that satisfies all the criteria at once.
This has two downstream consequences. First, the matching process itself is time-consuming and operationally demanding. Second, matched pairs designs require more participants than within-subjects (repeated measures) designs to generate the same number of data points — because each condition gets a different person rather than the same person twice. If participant availability is your binding constraint, a within-subjects design may simply be more efficient.
Perfect matching is also impossible in practice. Some participant variability always remains uncontrolled, which means the design reduces confounding rather than eliminating it.
Risks of imperfect matches
When matches are poor — when the paired participants aren't actually comparable on the variables that matter — the design can give you false confidence. You've gone through the effort of pairing, so the analysis treats the groups as balanced, but residual confounding is still distorting your treatment effect estimate. The comparison looks controlled when it isn't.
Imperfect matching creates a specific credibility problem: the analysis treats the groups as controlled when they aren't, which means your confidence intervals will be tighter than warranted. You'll report precision you didn't earn. That's a worse outcome than acknowledging the imbalance and adjusting for it post-hoc.
Simpler designs outperform matched pairs when their core conditions aren't met
Matched pairs designs are not always the right tool. When your sample is large enough that simple randomization will naturally balance groups across relevant variables, the additional complexity of matching may not be worth it — randomization achieves comparable control with far less operational overhead. When the variables you'd want to match on are difficult or expensive to measure before the experiment begins, the design becomes impractical regardless of its theoretical advantages.
If carryover effects aren't a concern and you have access to sufficient participants, a within-subjects design will typically give you more statistical efficiency than matched pairs. The decision comes down to what's actually constraining your experiment: if it's sample size and known sources of individual variation, matched pairs earns its complexity. If it's neither, simpler designs will serve you better.
Paired data requires a paired test — applying the wrong analysis discards the precision you built
Understanding the matched pairs experiment design is only half the work. The other half is analyzing the data it produces correctly — and this is where a surprisingly large number of researchers go wrong. Applying the wrong statistical test to paired data doesn't just reduce precision; it can invalidate your inference entirely.
Why matched data violates the independence assumption
The standard two-sample t-test assumes that each observation in your dataset has nothing to do with any other observation. In a matched pairs experiment, that assumption is false by construction. User A in the treatment group was deliberately paired with User B in the control group because they were similar — their outcomes are correlated.
If you ignore that link and run a standard independent-samples t-test, you're treating the pairing as if it never happened. You discard the precision the matching gave you. The correlation between paired observations is the whole point — your analysis needs to account for it, not pretend it isn't there.
This error is more common than it should be. As one practitioner noted in a widely-cited discussion of statistical misapplication in research: "To the majority, the unpaired T-Test is the only test that is needed. Ever. Doesn't matter if you have one or two tails, paired or unpaired trials, normally distributed population or skewed." The problem isn't obscure — it's systemic, and it's correctable.
Computing within-pair differences
The paired t-test resolves the dependency problem by reducing a two-sample problem to a one-sample problem. For each matched pair, you compute a single difference score: the treatment outcome minus the control outcome. The analysis then operates entirely on these difference scores, not on the raw group means.
As LatentView Analytics puts it directly, the "analysis is conducted on the difference between two related values rather than individuals themselves." This is the mechanical core of the method. Once you have a column of difference scores, the question becomes simple: is the mean of those differences significantly different from zero?
The paired t-test: mechanics, assumptions, and alternatives
Once within-pair differences are computed, the paired t-test is essentially a one-sample t-test applied to those differences. The key assumptions are that the differences are approximately normally distributed — or that the sample is large enough for the central limit theorem to provide cover — and that the pairs themselves are independent of each other, even though observations within a pair are not.
When normality of the differences cannot be reasonably assumed, the Wilcoxon signed-rank test is the appropriate non-parametric alternative. It makes no distributional assumption and operates on the ranks of the absolute differences rather than their raw values. For experiments where the outcome is binary or nominal rather than continuous — for instance, whether a user converted or didn't — the McNemar test is the correct choice. It uses the consistency of paired responses rather than their magnitude.
Permutation tests and when they're preferable
Permutation tests offer a distribution-free alternative that is particularly defensible when samples are small or outcome distributions are heavily skewed. Rather than relying on an assumed reference distribution, a permutation test constructs the null distribution empirically by repeatedly reassigning treatment labels within pairs and recalculating the test statistic.
The p-value is then the proportion of permuted statistics that are as extreme as or more extreme than the observed one. This approach makes minimal assumptions and can be more reliable than the paired t-test in exactly the conditions where the normality assumption is hardest to justify.
A significant result is only as credible as the design behind it
Whatever test you use, the output answers the same question: is the observed mean within-pair difference larger than would be expected from random fluctuation alone? A statistically significant result in a well-matched experiment carries stronger causal weight than in an unmatched design, precisely because the matching has already controlled for the confounders most likely to produce spurious effects. The p-value or confidence interval on the mean difference is your evidence — but the causal interpretability of that evidence depends on how well the experiment was designed in the first place.
For teams running experiments at scale, this is a reminder that design and analysis are inseparable. Modern experimentation platforms support multiple statistical frameworks — frequentist, Bayesian, and sequential methods including CUPED and post-stratification — reflecting the broader principle that the right analytical method must be matched to the experimental structure that produced the data. The same principle applies here: paired data requires a paired test, and choosing otherwise quietly discards the precision you worked to build.
Matched pairs design works when you know your confounders before the experiment starts
The through-line of this article is simple: most experiment failures are design failures. When the groups you're comparing were never truly comparable, no amount of analytical sophistication will save you. Matched pairs design is a direct response to that problem — it forces comparability before randomization begins, so the treatment effect you measure is doing the work you actually want it to do.
When to use a matched pairs design vs. simple randomization
The honest answer is that matched pairs earns its complexity in a specific set of conditions: small samples, strong prior knowledge about which variables predict your outcome, and the ability to measure those variables before treatment assignment. If you have a large, well-trafficked experiment where randomization will naturally balance groups, the overhead of matching may not be worth it. If you're running a tight clinical trial, a niche product test, or any experiment where imbalanced groups would be hard to detect and costly to explain, matching is worth the effort.
Two questions that determine whether matched pairs is the right tool
Before you commit to a matched pairs design, ask yourself two questions: Do I know which variables are most likely to confound my outcome? And can I measure them before I assign treatment? If the answer to either is no, you're better off with a well-randomized design and a post-hoc variance reduction method like CUPED — both core analytical methods in modern experimentation platforms — than with a matching process built on guesswork. The design rewards domain knowledge. If you have it, use it. If you don't, build it first.
The analysis must match the design
The analysis side is where good designs quietly get undermined. Paired data requires a paired test — the within-pair difference scores are the unit of analysis, not the raw group means. If your outcome is continuous and roughly normal, the paired t-test is your starting point. If it's skewed, reach for the Wilcoxon signed-rank test. If it's binary, McNemar is correct. The choice isn't academic — using the wrong test discards the precision you built into the design.
This article was written to be genuinely useful to practitioners who are trying to run cleaner experiments, not just understand the theory behind matched pairs design.
What to do next: If you're currently planning an experiment, start by writing down the two or three variables most likely to predict your outcome metric. If you can measure those variables before assignment and your sample is small enough that imbalance would matter, you have the conditions where matched pairs will pay off. If you can't measure them in advance, the variance reduction methods covered earlier apply — the goal is the same whether you control at design time or analytically after the fact.
Related Articles
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.
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.
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.
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 GuideThe 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.
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.
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.
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.
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, that's the point to consider managed 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 GrowthBookTwo 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.
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.
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.
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 GuideCreate 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.
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.
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.
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.
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 GrowthBookYour 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.
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.
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.
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 GuideThe 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.
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.
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.
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.
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.
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.
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 GrowthBookReady to ship faster?
No credit card required. Start with feature flags, experimentation, and product analytics—free.



