How to calculate a power analysis

An experiment can run exactly as planned and still have almost no chance of answering the question that justified it.
That happens when a team launches without checking whether its traffic, metric variance, and expected effect can produce a decisive result. The test accumulates data for weeks. The variation looks slightly better, then slightly worse. Nobody knows whether the feature had no effect or the experiment simply could not detect it.
Power analysis prevents that ambiguity from being a surprise. It connects the effect you care about, the error rates you will tolerate, and the sample you can collect. The output is not a promise that an experiment will succeed. It is a design constraint: under the assumptions you chose, this is how much information the test needs to have a specified chance of detecting a real effect.
This guide explains the mechanics, shows a practical A/B testing example, and turns the calculation into a planning workflow product and data teams can use before launch.
What power analysis tells you
Statistical power is the probability that a hypothesis test rejects the null hypothesis when a specific alternative is true. Equivalently, power is 1 - beta, where beta is the probability of a Type II error: failing to detect an effect that really exists. Penn State's statistical curriculum illustrates the relationship by comparing the null and alternative sampling distributions and measuring how often the test correctly rejects the null.
A power analysis solves for one unknown while the other design inputs are fixed. Teams most often use it to estimate required sample size, but it can answer several questions:
- How many experimental units does the test need?
- What effect size can the available sample reliably detect?
- What power will the test have at a fixed sample size?
- How does a stricter significance threshold change the required sample?
- How long will it take to accumulate enough eligible users or events?
In product experimentation, the sample-size question is usually the most operationally useful. If a checkout experiment needs 40,000 eligible users per variation and the product sees 5,000 eligible users per week, the team can estimate an eight-week minimum collection period before launch. That estimate can expose an infeasible test while there is still time to change the metric, population, effect threshold, or product plan.
This is why power belongs in experiment design, not in the final analysis. GrowthBook's guide to A/B testing places power analysis before the test starts: both Bayesian and frequentist workflows benefit from understanding what sample is required to detect the effect the team cares about.
Power does not measure the probability that your hypothesis is true
An 80% powered test does not mean there is an 80% chance the treatment works. It means that if the true effect equals the effect used in the calculation, the planned statistical procedure will detect it about 80% of the time over repeated experiments.
That conditional wording matters. Power depends on an assumed effect. A test designed for a five-percentage-point increase may have strong power for a five-point effect and weak power for a one-point effect. The calculation describes the sensitivity of a design, not the truth of a product hypothesis.
Power also does not guarantee a statistically significant result. Even a well-powered experiment can be inconclusive. At 80% power, a test still has a 20% Type II error rate for the assumed alternative. The point is to make that risk explicit and acceptable before spending traffic and engineering time.
Power connects practical and statistical significance
Teams often choose an effect size by asking what lift they hope to see. That is the wrong starting point. The better question is: what is the smallest effect that would change the decision?
This minimum detectable effect, or MDE, turns business judgment into a statistical input. If a 0.2% relative lift would never repay implementation and maintenance costs, powering a test to detect it wastes traffic. If a 1% decline in payment completion would create unacceptable financial or customer harm, the experiment may need enough power to detect a change that small.
The MDE therefore acts as a contract between product value and statistical sensitivity. GrowthBook's article on statistical validity demonstrates the time-dependent tradeoff: early in a test, only large effects are detectable; as the sample grows, the MDE shrinks.
The four inputs that drive statistical power
For a standard two-group test, four quantities determine one another: effect size, significance level, power, and sample size. Fix any three and you can solve for the fourth.
| Input | What it represents | What happens when it increases |
|---|---|---|
| Effect size or MDE | The smallest true difference the design should detect | Larger effects require less sample |
| Significance level (alpha) | The tolerated probability of a Type I error under the null | A larger alpha increases power but allows more false positives |
| Desired power | The chance of detecting the specified effect | Higher power requires more sample |
| Sample size | The number of independent experimental units | More units increase power, all else equal |
These inputs are not interchangeable business preferences. Each represents a different risk or resource constraint.
Effect size must match the metric
Effect size can be expressed as an absolute difference, relative lift, or standardized difference. The calculation must match the outcome and statistical test.
For a binary conversion metric, moving from 10% to 11% is a one-percentage-point absolute change and a 10% relative lift. For a continuous metric such as revenue per user, power depends on the difference in means relative to the metric's variance. For a count or ratio metric, a normal approximation may not fit, especially with heavy tails or many zeros.
Libraries encode those distinctions. For example, the official 0 proportion effect-size function transforms two proportions for use in a normal-approximation power calculation. A t-test power function expects a standardized mean difference instead. Feeding a relative percentage lift directly into the wrong function can produce a precise but meaningless sample size.
Alpha and power represent different errors
Alpha controls Type I error: declaring an effect when the null model is true. Beta controls Type II error: missing the specified effect when it is real. Reducing one error without changing anything else usually increases the other. Penn State's sample-size treatment makes the escape hatch explicit: increase the sample if you want both a low alpha and a low beta.
Common planning defaults are a two-sided alpha of 0.05 and power of 0.80. They are conventions, not laws. A test governing a low-risk interface preference may tolerate different tradeoffs than a test affecting fraud detection, loan approvals, or medication adherence. The important practice is to choose the thresholds before observing results and justify them based on the decision.
Sample size means independent experimental units
Power calculations operate on independent units, not arbitrary rows. If users are randomized but the dataset contains sessions, clicks, or purchases, counting every event as a separate sample inflates the apparent information. The experiment may have one million events but only 10,000 independently assigned users.
The distinction becomes more important in cluster-randomized designs. If a team randomizes companies, classrooms, or geographic regions, observations within each cluster tend to be correlated. The effective sample size is closer to the number and diversity of clusters than the raw event count. GrowthBook's guide to experimental units explains why the entity receiving treatment must match the unit used for inference.
Make every sample count
Learn how CUPED and other variance-reduction methods can improve experiment sensitivity when pre-period data predicts the outcome.
Explore Variance ReductionHow to perform a power analysis before an A/B test
A useful power analysis is less about typing numbers into a calculator and more about defending the inputs. The following workflow works for a conventional two-variation product experiment.
1. State the decision and hypothesis
Write down what the team will do if the treatment wins, loses, or remains inconclusive. Then specify the primary metric and the population eligible for the change.
Suppose a team is testing a new onboarding sequence. The primary outcome is activation within seven days. The existing activation rate is 20%. The team would ship the sequence if it improves activation by at least two percentage points without harming retention or support contacts.
That produces a clear planning statement:
- Control rate: 20%.
- Smallest worthwhile treatment rate: 22%.
- Absolute MDE: 2 percentage points.
- Relative MDE: 10%.
- Randomization unit: user.
- Test: two-sided comparison of two independent proportions.
The two-sided choice allows the experiment to detect a meaningful decline as well as an improvement. A one-sided test can require less sample, but it is only defensible when effects in the untested direction genuinely would not affect the decision.
2. Estimate the baseline and variance from relevant history
Use recent data from the same metric definition, eligibility rule, and unit of analysis. A sitewide conversion rate is a weak baseline for an experiment shown only to new mobile users. A revenue metric from holiday traffic may not represent a test planned for February.
Pull enough history to see weekly patterns and estimate the eligible population. Check whether metric variance changes substantially across segments or time. If the planned treatment affects a new surface with no direct history, use the closest analog and run a sensitivity analysis instead of pretending the estimate is exact.
This is one advantage of warehouse-connected planning. GrowthBook's experimentation product can use existing metric definitions and historical data rather than making a team re-create its measurement logic in a disconnected calculator.
3. Choose alpha, desired power, and allocation
For a conventional planning scenario, the team might choose:
- Two-sided alpha: 0.05.
- Desired power: 0.80.
- Allocation: 50% control and 50% treatment.
An equal split generally maximizes power for a fixed total sample when observations have similar cost and variance in both groups. Unequal allocation may be justified when treatment exposure is risky or expensive, but the total required sample will usually increase.
If the experiment tracks many primary outcomes or variations, adjust the design for multiple testing. A sample-size calculation for one clean comparison does not automatically protect a dashboard containing twenty chances to find a favorable result.
4. Calculate sample size with the correct test
For two proportions, software typically uses a normal approximation or a closely related method. For two means, the calculation uses the expected standard deviation and mean difference. Paired tests, cluster designs, survival outcomes, and noninferiority tests need their own procedures.
Using a standard two-sided calculation for the onboarding example—20% control, 22% treatment, alpha 0.05, 80% power, and equal groups—produces a requirement of roughly 6,500 users per variation, or about 13,000 total. Exact results vary slightly by method and continuity correction, which is why the team should record the software, function, and assumptions used.
The code can be short:
Treat that output as the start of planning, not the end. Confirm that the approximation fits the metric, units are independent, and expected counts are large enough. The broader SAS guide to power and sample-size analysis recommends what-if analysis because required sample size can be highly sensitive to uncertain inputs.
5. Convert the sample into a realistic duration
If 4,000 eligible users enter onboarding per week, a 13,000-user test might appear to need 3.25 weeks. Real duration planning should also account for:
- Traffic allocated to the experiment.
- Users excluded by targeting or activation rules.
- Delayed outcomes, such as seven-day activation.
- Weekly seasonality and minimum exposure cycles.
- Data latency and validation time.
- Expected sample loss from bot filtering or missing identifiers.
If only 80% of eligible users trigger the experiment and the metric needs seven days to mature, the calendar duration extends beyond the simple traffic division. Record both the assignment target and the earliest responsible analysis date.
Reddit's engineering team describes a similar sequence in its ads experiment process: define the hypothesis and audience, conduct pre-experiment power analysis, and use it to determine minimum duration before validating the setup with an A/A test.
6. Run sensitivity scenarios
Effect size is usually the least certain input. Calculate at least three scenarios:
- Optimistic: the lift the strongest evidence supports.
- Expected: the team's best defensible planning estimate.
- Conservative: a smaller effect that would still matter.
The output may reveal that a 10% relative lift is detectable in three weeks, while a 5% lift requires twelve. That is valuable product information. It forces the team to decide whether the smaller effect is worth waiting for and whether the experiment surface has enough traffic.
GrowthBook's analysis of traffic requirements for AI features recommends this scenario-based approach because variance and effect estimates are often uncertain. The lesson applies beyond AI: a single assumed lift hides how fragile the plan is.
Common power analysis mistakes
The calculation is easy to automate. The failure modes are mostly conceptual.
Choosing the effect after seeing the result
An observed effect is a noisy estimate of the population effect. Plugging it into a post-hoc power calculation largely recycles the same information already expressed by the p-value. It can also make a lucky, exaggerated estimate look like evidence that the study was well designed.
After an experiment, report the effect estimate and confidence or credible interval. Ask whether the interval excludes effects that would change the decision. Do not use observed power to retroactively certify the design.
Treating “not significant” as “no effect”
An underpowered test that fails to reject the null does not show equivalence. It may mean the effect is zero, smaller than the MDE, or simply obscured by noise. GrowthBook's explanation of experimental probability frames sample size as a design input precisely because an inconclusive result otherwise leaves these possibilities tangled together.
If the business question is whether two experiences are sufficiently similar, use an equivalence or noninferiority design with an explicit margin. A superiority test that fails is not a substitute.
Using the wrong baseline or denominator
Powering on pageviews when users are randomized, using all-site traffic for a targeted experiment, or using overall conversion for a rare segment can understate duration dramatically. Align the historical query with the actual exposure and analysis population.
Also distinguish assigned users from activated users. If many assigned users never encounter the changed feature, intent-to-treat dilution can shrink the observed effect and increase the sample needed. Decide how activation will be handled before launch rather than filtering opportunistically after results arrive.
Ignoring metric variance and clustering
Binary conversion calculators are convenient, but not every product metric is binary. Revenue per user is often skewed. Repeated observations within a user are correlated. Teams and accounts create clusters. A generic calculator that assumes independent, normally distributed observations may be optimistic.
Simulation is often the better approach for complex metrics. Generate synthetic assignments from historical units, inject plausible treatment effects, apply the planned estimator, and measure how often the decision rule detects the effect. This preserves more of the real metric distribution and analysis pipeline than a closed-form approximation.
Peeking without a sequential design
A fixed-horizon calculation assumes the team follows the planned analysis rule. Repeatedly checking a conventional p-value and stopping as soon as it crosses 0.05 changes the false-positive behavior. Reaching the sample target eventually does not repair a stopping rule that depended on interim results.
If continuous monitoring is operationally important, use a valid sequential method and power the actual decision procedure. GrowthBook supports sequential testing alongside Bayesian and frequentist analysis, but the method still needs a pre-specified decision policy. “Stop when the chart looks convincing” is not a statistical design.
How to improve power when traffic is limited
“Get more users” is only one way to improve power. Teams can often make the signal cleaner.
First, choose one primary metric closely connected to the treatment. A noisy or distant business outcome may be important as a guardrail but inefficient as the main decision metric. Second, improve instrumentation and assignment integrity. Missing exposures and inconsistent identifiers add noise that no formula can remove.
Third, reduce unexplained variance. Covariate adjustment can use pre-experiment behavior that predicts the outcome. CUPED, for example, adjusts the analysis using correlated pre-period data. Matched or blocked designs can help in settings where strong confounders are known, although they change the analysis and must be planned correctly. GrowthBook's guide to matched-pairs experiments explains why design-based balance can improve precision for smaller samples.
Fourth, test a larger product difference. When traffic cannot support detecting a tiny lift, the rational response may be to stop testing cosmetic changes and develop a stronger hypothesis. Power analysis is useful even when it says “do not run this test.” It prevents a low-information experiment from consuming weeks of attention.
Finally, narrow the decision. If the team cannot power every segment interaction, pre-specify the population and effect that matter most. Exploratory segment analysis can generate future hypotheses, but it should not quietly redefine the original success criterion.
Make power part of the experiment contract
A power analysis should leave behind a short, reviewable record:
- Primary metric and exact definition.
- Experimental unit and eligible population.
- Baseline estimate and historical window.
- Minimum detectable effect in absolute and relative terms.
- Alpha, target power, test direction, and allocation.
- Required sample per variation.
- Expected enrollment rate and minimum duration.
- Statistical test or simulation procedure.
- Sensitivity scenarios and major assumptions.
- Planned handling of interim monitoring and delayed outcomes.
That record turns “we need more data” from a vague reaction into a decision the team made before launch. It also makes disagreements productive. Product can challenge whether the MDE is commercially meaningful. Data can challenge the variance estimate or test choice. Engineering can challenge whether the eligible traffic estimate matches actual exposure.
Power analysis will not rescue a weak hypothesis, broken instrumentation, or biased assignment. It does something more foundational: it tells you whether the experiment you designed has a reasonable chance of answering its own question.
Plan and analyze in one place
Use warehouse-defined metrics, power-aware experiment plans, and shared results to move from sample sizing to a defensible decision.
Get Started With GrowthBookRelated 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, 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 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. 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 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. 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 GrowthBookReady to ship faster?
No credit card required. Start with feature flags, experimentation, and product analytics—free.





