Experiments
Feature Flags

7 Statsig alternatives for A/B testing and experimentation

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

A Statsig alternative must preserve the chain from assignment to decision. Perfect assignment still fails when exposures, units, metrics, or stopping rules are wrong.

Statsig combines flags, experiments, product analytics, and related product-data workflows. Some alternatives replace that full surface; others specialize in warehouse analysis, release testing, visual optimization, or product analytics.

OpenAI acquired Statsig in 2025, while Amplitude said it would develop the Statsig platform across cloud and warehouse deployments and support existing customers. Portability, roadmap clarity, and contract terms therefore belong in the evaluation.

This guide compares GrowthBook, Datadog Experiments, Optimizely, Kameleoon, LaunchDarkly, PostHog, and VWO. GrowthBook is the strongest overall recommendation because it combines feature delivery, rigorous experimentation, warehouse flexibility, open-source deployment, and predictable pricing.

Statsig experimentation alternatives at a glance

AlternativeBest fitData and analysis modelMain watchout
GrowthBookTechnical product, data, and engineering teamsWarehouse-native or managed warehouse; Bayesian, frequentist, sequential, and variance reduction optionsAdvanced governance and methods span paid tiers
Datadog ExperimentsData-mature teams that want Eppo methods plus Datadog contextWarehouse-native metrics with Eppo's statistical engine and observability integrationProduct transition and public pricing require direct evaluation
OptimizelyLarge programs spanning web and feature experimentationVendor event pipeline plus warehouse-native analytics options; several statistical enginesIndividually packaged pricing and product boundaries can add complexity
KameleoonHybrid web, product, and feature experimentation programsClient, server, and warehouse-connected workflows with flexible statisticsFull-stack capabilities and advanced methods depend on packaging
LaunchDarklyExperiments coupled tightly to feature releasesFlag-based assignment, event or warehouse metrics, Bayesian and frequentist analysisMultiple usage meters and a release-first product center of gravity
PostHogSmall technical teams wanting analytics, replay, flags, and tests togetherPostHog event model or data warehouse sources; Bayesian and frequentist analysisBroad usage-based platform creates several cost and governance surfaces
VWOConversion teams running visual web and server-side testsWebsite-oriented testing with feature experimentation and Bayesian reportingTechnical depth and package scope vary across Testing and Feature Experimentation

What to compare before choosing a Statsig replacement

Use the OpenFeature specification as an independent reference for evaluation APIs.

Randomization unit, assignment, and exposure

Choose the experimental unit before the tool. Consumer experiences often randomize a person or device. B2B products may need an account, workspace, or organization because members share the treatment. Marketplaces may require switchback or cluster designs because participants affect one another.

The platform needs a stable assignment key and consistent allocation across web, mobile, server, and edge runtimes. Test null values, identity transitions, retries, and SDK-version differences. Sticky assignment prevents variant changes but creates state that must be migrated.

Exposure is not the same as eligibility or assignment. Log a participant when the treatment can actually affect them, not merely when a page loads or a flag definition exists. Triggered analysis can improve sensitivity, but only if the trigger is not changed by treatment in a way that introduces selection bias. The broad research literature on statistical challenges in online controlled experiments treats exposure, interference, sensitivity, long-term effects, and optional stopping as connected design problems rather than dashboard settings.

Metric source and semantic governance

A good alternative makes the metric definition inspectable. Record source tables or events, joins, aggregation unit, attribution window, exclusions, outlier policy, late-data behavior, and version. A metric named revenue is not governed if one tool uses checkout events while finance uses settled payments net of refunds.

Warehouse-native analysis can reuse modeled data and run calculations near the source. An event-native platform can be faster to start and may pair naturally with real-time product analytics. Neither architecture guarantees correctness. Compare query reproducibility, freshness, compute cost, backfill behavior, row-level security, personal-data movement, and how a changed metric definition affects completed experiments.

For cross-product effects, keep assignment rows even when a subject produces no downstream event. Microsoft's guidance on A/B testing across products explains why joining only participants who appear in a second product can bias the analysis. The proof of concept should reproduce at least one metric outside the vendor UI from raw assignments, exposures, and outcomes.

Statistical method and stopping policy

Bayesian, fixed-horizon frequentist, and sequential methods answer related questions with different assumptions and decision language. The tool should document what it calculates, how priors or significance thresholds are chosen, how repeated looks are handled, and whether confidence or credible intervals remain valid under the team's actual stopping behavior.

Start from the decision risk: false launches, missed improvements, practical effect size, duration, and the cost of continuing a harmful treatment. Predefine the primary metric, guardrails, minimum detectable effect, analysis method, minimum runtime, and decision thresholds.

Multiple metrics and many variants increase the chance of a chance finding. Ask whether the platform applies a family-wise or false-discovery correction, whether it distinguishes a designated primary metric from exploratory metrics, and how segment exploration is labeled. Microsoft's paper on metric interpretation pitfalls is a useful reminder that trustworthy counts do not rescue a poorly defined decision metric.

Variance reduction, power, and data quality

CUPED and related covariate adjustment methods can improve precision by using information collected before treatment. The original Microsoft research on improving sensitivity with pre-experiment data is the conceptual baseline. Implementations differ in eligible metric types, lookback windows, covariates, outlier handling, missing history, segmented results, and how often models refresh. Ask for method documentation and compare adjusted and unadjusted outputs on known experiments.

Every finalist should detect sample ratio mismatch. SRM means the observed assignment or exposure counts differ more than expected from the configured split. It is a symptom, not an inconvenience to dismiss. Microsoft's SRM taxonomy and diagnostic guidance covers causes such as logging loss, redirects, filters, inconsistent identifiers, and variant-dependent execution. A platform should block or clearly quarantine conclusions until the root cause is understood.

Power calculators should use the same unit, variance, and metric construction as the experiment. Validate them against historical traffic. A low-traffic team often gets more value from narrowing the population, choosing a more sensitive proximal metric, reducing measurement noise, or testing a larger product change than from changing the color of the statistical badge.

Program operations and governance

Compare hypothesis templates, review checklists, mutually exclusive layers, holdouts, approvals, reports, audit logs, APIs, and decision history. Use risk tiers: a copy test may need peer review, while billing, ranking, or permission experiments may need data-science, legal, and operational sign-off.

1. GrowthBook: Best overall Statsig alternative

Best for

GrowthBook is the best fit for technical product organizations that want to keep experiment metrics in an existing warehouse, or start with a managed warehouse and retain a path to bring their own data later. It combines experimentation, feature flags, and product analytics without requiring one analytics architecture for every team.

It is also the clearest choice for buyers who want an inspectable open-source core and a supported hosted product. That deployment flexibility makes it easier to treat the current Statsig transition as an opportunity to reduce platform lock-in rather than merely swap one closed SaaS endpoint for another.

Key strengths

GrowthBook can query experiment assignments and outcomes from a warehouse, so data teams can reuse governed facts, dimensions, and SQL. Teams without that infrastructure can use the managed ClickHouse-backed path and migrate later. The practical advantage is not the phrase “warehouse native”; it is having one auditable definition for revenue, retention, activation, or cost across experiments and business reporting.

The statistical surface covers Bayesian and frequentist analysis, multiple-testing corrections, SRM detection, guardrails, and shareable results on the free tier. Pro adds sequential testing, CUPED variance reduction, sticky bucketing, power calculations, decision frameworks, and multi-armed bandits. Enterprise adds program-level controls such as holdouts, launch checklists, custom metadata, stronger access control, and audit capabilities. The public GrowthBook pricing page makes those boundaries unusually visible.

Assignment runs in SDKs using deterministic hashing, while experiment analysis can stay separate from delivery. That separation is useful during migration: a team can analyze a historical Statsig test in GrowthBook before replacing assignment, or use a different flag provider while validating the analysis layer. It also supports gradual adoption across stacks rather than a flag-day migration.

Watchouts

Warehouse-native analysis needs disciplined data modeling. Bad joins, identity drift, expensive scans, or inconsistent exposure tables remain bad even when the UI makes them easier to query. Assign an owner to each data source and metric, set cost controls, and test late-arriving events and backfills.

Some mature-program capabilities are paid. Teams that need holdouts, approval workflows, advanced access control, SSO, SCIM, or formal support should compare the relevant GrowthBook tier with the actual Statsig contract, not compare an open-source screenshot with an enterprise deployment.

Pricing and implementation notes

The Cloud Starter plan is free for up to three users and includes unlimited flags, experiments, and traffic. Pro is currently $40 per seat per month and adds the advanced experimentation methods most scaling teams expect. Enterprise is custom. The self-hosted open-source plan is free with unlimited users, flags, experiments, and traffic; supported enterprise self-hosting is custom.

For a proof of concept, connect one representative data source, import or recreate a completed experiment, define one binary metric, one revenue or ratio metric, and one guardrail, then compare counts and intervals with the old result. Run an A/A test through the production SDK path before moving decision-critical traffic. The GrowthBook versus Statsig comparison provides a product-level starting point, but the organization's raw-data reconciliation should decide the migration.

2. Datadog Experiments: Best for warehouse metrics plus observability

Best for

Datadog Experiments is the successor path for teams attracted to Eppo's warehouse-native experimentation and advanced statistics, especially when Datadog already owns application observability and product analytics. Datadog acquired Eppo in 2025 and launched Datadog Experiments in 2026, combining warehouse business metrics, product events, and operational guardrails.

That combination is differentiated for backend, AI, performance, and reliability experiments. A model or ranking change may affect conversion, latency, error rate, infrastructure cost, and token consumption at once. Keeping technical guardrails close to traces and application telemetry can shorten diagnosis when a statistically promising treatment harms service quality.

Key strengths

Eppo's warehouse-native model remains the statistical foundation. Its documentation describes frequentist fixed-sample, sequential, hybrid-sequential, and Bayesian choices, along with SRM checks, winsorization, sample-size planning, and CUPED++. CUPED++ can use historical values from multiple eligible metrics and assignment properties as covariates, rather than limiting adjustment to the pre-period value of the same outcome.

The metric layer can be defined through a UI or a code-based semantic framework. That is useful for data teams that want reviewed, versioned definitions and for product teams that need a readable catalog. Eppo also supports layers, mutual exclusion, global holdouts, entry points, and analyses over assignments produced by another system.

The current Datadog Experiments launch announcement positions the product around warehouse business metrics, product analytics events, and real-time observability guardrails. This can make it a strong replacement when Statsig experiments were already paired with Datadog dashboards and incident workflows.

Watchouts

Treat the Eppo-to-Datadog transition as a product migration to evaluate, not merely a new logo. Ask which functions live in the Datadog Experiments application today, which remain in Eppo interfaces, how existing customers are being migrated, and whether SDKs, APIs, metric definitions, links, and data-retention terms will change. Datadog has publicly described an active customer migration and roadmap, so current-state evidence matters more than older comparison pages.

Warehouse analysis can also create significant compute. Measure scanned bytes, cache reuse, refresh duration, concurrency, and the behavior of wide metric sets. CUPED++ is powerful, but buyers should understand where it applies and note that Eppo's documentation says adjusted results are not available for every filtered or exploratory view.

Pricing and implementation notes

Public self-serve pricing for Datadog Experiments is not clearly posted, so request a written quote and meter definition. Include experiment subjects, assignments, warehouse compute, product-analytics events, observability data, feature-flag traffic, seats, retention, support, and migration services. If the organization already has a Datadog commitment, ask how Experiments changes the committed-spend model.

The proof of concept should use a change with both a business metric and a technical guardrail. Compare a warehouse result, a product event, and an observability signal on the same experimental unit. Verify identity joins and timestamps, then reproduce the effect estimate from exported assignments and outcomes. This tests the integration value that distinguishes Datadog Experiments from a standalone statistical dashboard.

Compare GrowthBook and Statsig

See how warehouse-native experiments, open-source deployment, feature flags, and predictable pricing compare with Statsig.

Explore the comparison

3. Optimizely: Best for a broad enterprise experimentation program

Best for

Optimizely fits organizations that want a mature program spanning visual web tests, feature and server-side experiments, personalization, collaboration, and warehouse-native analysis. It is strongest when experimentation is a cross-functional enterprise capability rather than a tool used by one product squad.

The product family can support marketers editing a webpage, engineers testing a backend algorithm, analysts exploring segments, and program leaders managing ideas and results. That breadth is valuable when consolidation is the goal and the organization has owners for platform architecture, implementation, and statistical policy.

Key strengths

Optimizely Feature Experimentation uses SDKs and a CDN-delivered datafile to run flags and tests across applications. The current Feature Experimentation documentation describes unlimited flags and controlled rollouts on the free Rollouts tier, with one concurrent experiment; paid plans add the full Stats Engine, collaboration, governance, and greater capacity.

Optimizely's newer results experience supports frequentist fixed-horizon, sequential, and Bayesian engines, plus CUPED, outlier management, exploration, and data-health checks. The established Stats Engine includes confidence intervals and false-discovery-rate control. The broader experimentation portfolio adds visual editing, multivariate tests, bandits, audience targeting, and personalization. Warehouse-native analytics can centralize analysis over governed data while web and feature products handle delivery.

For a large organization, program-management features and services can matter as much as calculations. Optimizely can provide structured collaboration, permissions, support, and training across many teams. It is a credible choice when the buyer wants one strategic vendor for marketing and product experimentation and is prepared to manage product boundaries.

Watchouts

Breadth creates architecture and procurement work. Establish which product performs assignment, which stores events, which computes results, and which owns the experiment record. “Optimizely Experimentation” can refer to different combinations of Web Experimentation, Feature Experimentation, Analytics, Personalization, and collaboration capabilities. A capability in one package should not be assumed to exist in another.

The new A/B results page has its own eligibility limits; Optimizely's documentation says, for example, that it applies to manual A/B experiments and not every adaptive or multivariate design. Confirm the exact statistical engine and result interface for each planned experiment type. If teams mix methods, encode the choice in templates so experimenters cannot select a friendlier-looking answer after seeing data.

Pricing and implementation notes

Optimizely says paid experimentation deployments are individually packaged based on traffic, products, and implementation complexity. Rollouts offers a free entry point with one experiment at a time, but an enterprise comparison requires a quote. Ask for separate and bundled pricing across web testing, feature experimentation, warehouse analytics, personalization, collaborators, monthly active users, raw-event export, support, and professional services.

Use two proof-of-concept tracks if both marketer and product use cases matter: a visual web test that checks flicker, performance, consent, and editor workflow; and a server-side flag experiment that checks deterministic assignment, event export, metric reconciliation, and rollback. Do not let a strong visual-editor demo substitute for the feature-experiment evidence, or vice versa.

4. Kameleoon: Best for hybrid web and feature experimentation

Best for

Kameleoon is a strong option for organizations that need one experimentation program across websites, applications, server-side features, and product teams. It sits between web-optimization suites and developer-first feature platforms: non-engineers can create visual tests, while engineers can run SDK-based experiments and controlled releases.

It is especially relevant when the statistical team wants a choice among methods rather than one mandatory engine. Kameleoon publishes detailed methodology covering assignment, frequentist tests, multiple-test correction, CUPED, sequential tests, Bayesian decisions, continuous metrics, outlier handling, and bandits.

Key strengths

Kameleoon supports visual and code-based experimentation, feature flags, audience targeting, holdouts, mutually exclusive groups, raw-data access, and web performance controls. Its current plans page lists sequential testing, multiple-testing correction, SRM detection, unlimited metrics and audiences in the PBX Starter package, with feature management, feature experimentation, CUPED, personalization, mobile testing, and bandits available in the broader enterprise configuration.

The statistics are more transparent than a generic “AI-powered significance” claim. Kameleoon documents fixed frequentist and Bayesian approaches, sequential confidence sequences, multiple-comparison controls, power planning, and CUPED using pre-experiment outcomes. It also warns users not to toggle between adjusted and unadjusted results after observing which looks more favorable, an important operational detail.

The hybrid delivery surface is useful for gradual organizational adoption. A conversion team can start with browser tests, while engineering adopts server-side experiments for pricing logic, recommendations, or application flows. A common result and governance layer can reduce the split between “marketing tests” and “product experiments.”

Watchouts

Package mapping is essential. The public plans page distinguishes the prompt-based starter from enterprise add-ons, so feature experimentation and advanced statistical capabilities should be confirmed in the quote. Ask whether each method applies to client-side, server-side, and warehouse-connected experiments, and whether filtered or segmented results use the same adjustment.

Browser testing introduces familiar risks: flicker, content security policy, consent interactions, tag-manager timing, single-page application navigation, and page-performance impact. Server-side testing avoids several browser constraints but requires engineers to implement assignment and exposure correctly. Test both paths rather than assuming a “unified” platform makes them operationally identical.

Pricing and implementation notes

Kameleoon currently advertises a 30-day free PBX trial for up to three experiments and a PBX Starter package beginning at $495 per month for up to ten experiments and 50,000 tested visitors per month. Enterprise is custom. The starter price does not represent every feature-experimentation requirement, so obtain a line-item proposal for tested traffic, projects, environments, web domains, feature flags, advanced methods, raw export, support, and service levels.

For the proof of concept, run the same business hypothesis through one visual implementation and one server-side implementation. Compare assignment stability, exposure counts, SRM checks, page performance, raw export, and statistical output. This reveals whether the cross-functional promise survives real implementation boundaries.

5. LaunchDarkly: Best for release-centric experimentation

Best for

LaunchDarkly is best when experiments are extensions of software delivery. Engineers already wrapping changes in flags can attach metrics, run a test, inspect uncertainty, and roll the winning variation forward without moving the release workflow to a separate system.

It can replace Statsig for teams using flags and experiments more heavily than Statsig's analytics and replay products. It is less obviously a one-for-one replacement when the organization expects the experiment vendor to be its primary product-data platform.

Key strengths

LaunchDarkly supports A/B/n tests, funnel metrics, A/A validation, mutually exclusive experiments, holdouts, multi-armed bandits, and experiments over flags across client, server, mobile, edge, and infrastructure contexts. Its experimentation documentation describes both Bayesian and frequentist analysis, uncertainty intervals, targeting, performance and cost metrics, and warehouse-native metrics.

The release connection is the core advantage. A treatment can be guarded by the same targeting and kill-switch infrastructure used for normal delivery. Product managers can test a feature while engineering retains control over rollout, and operations teams can include latency, error, or cost outcomes. A platform already standardized on LaunchDarkly flags may avoid a second assignment SDK.

The documentation is unusually explicit about experiment design. It distinguishes assignment keys, sample-size planning, metric types, mutually exclusive layers, and holdouts. The migration guidance also recognizes Statsig as a source platform, which can reduce mapping work for flags and experiment definitions.

Watchouts

Release-centric experimentation still needs a governed metric layer. Inventory whether each result uses LaunchDarkly events, warehouse-native metrics, or Data Export, and reconcile the result with business reporting. Flag exposure telemetry is not automatically the correct analysis population; test evaluation timing and repeated calls in the application's actual code path.

Pricing has several meters. Experimentation usage can be measured separately from service connections, client-side users, observability data, session replay, and other platform capabilities. Model a year of growth and concurrent experiments rather than pricing one small test. Also confirm which statistical, governance, and warehouse functions belong to the selected plan.

Pricing and implementation notes

The current free Developer plan includes unlimited flags and seats, five service connections, 1,000 client-side monthly active users, and 100,000 experimentation MAU per month. Paid plans scale through usage-based and custom packaging. Use the LaunchDarkly pricing page for the current meters, then request a quote based on server environments, client users, experiment keys, and expected growth.

The proof of concept should instrument a production-shaped flag across at least two SDK runtimes. Verify deterministic assignment, session consistency, exposure deduplication, offline behavior, warehouse or event-metric counts, and the path from a stopped experiment to a normal rollout. Run an A/A test before trusting a feature-change result.

6. PostHog: Best all-in-one choice for a small technical team

Best for

PostHog fits small engineering-led product teams that want product analytics, session replay, feature flags, experiments, error context, and warehouse data in one interface. It is fast to evaluate, transparent about usage pricing, and broad enough to replace several Statsig workloads without an immediate procurement process.

The product is most compelling when the team is comfortable using PostHog's event and identity model as a central product-data layer. A team that already has deeply governed warehouse metrics should test data-warehouse sources and reconciliation carefully rather than recreating every metric in the event pipeline.

Key strengths

Experiments attach to feature flags and can use funnel, mean, ratio, and other saved metrics. PostHog supports Bayesian analysis by default and a frequentist option. Its public Bayesian methodology describes user-level aggregation, effect estimation, uncertainty, and quality checks instead of hiding the calculation entirely.

The surrounding context is the differentiator. A result can be explored alongside funnels, cohorts, recordings, user behavior, and errors. Engineers can move from a metric change to sessions or diagnostic events without stitching together several vendors. Flags and analytics also share identity and event infrastructure, which can simplify early implementation.

PostHog exposes APIs and maintains an open-source core, which can suit teams that prefer inspectable infrastructure and agent-driven workflows. Its generous free allowances let a startup run a realistic trial before negotiating an annual contract.

Watchouts

The all-in-one model creates coupling. Identity mistakes, ingestion loss, or event-schema drift can affect analytics and experiment decisions at once. Define canonical subject IDs, event ownership, schema checks, and metric reviews before many teams self-serve. Verify how anonymous identity merges, group analytics, late events, and feature-flag calls influence exposure.

PostHog's supported production path is cloud. Although the core repository and a Docker Compose deployment are public, its self-hosting documentation says self-hosted deployments are officially unsupported, have no paid support or guarantees, and cannot use paid-plan features. Do not choose it as a supported on-premises Statsig replacement without accepting that constraint.

Usage-based pricing also spans multiple products. An experiment can consume feature-flag requests and product-analytics events, while replay, warehouse, error tracking, and other products have their own meters. The per-unit price can look small while the combined data surface grows quickly.

Pricing and implementation notes

PostHog currently includes free monthly allowances of one million product-analytics events, one million feature-flag requests, and 5,000 session recordings. Paid product analytics starts at $0.00005 per event and feature flags at $0.0001 per request, with volume pricing. Confirm current allowances and regional options on the PostHog pricing surface before committing.

For the proof of concept, instrument one feature experiment plus one existing analytics funnel. Compare raw event volume, unique experimental subjects, exposures, conversions, identity merges, and replay availability. Then model a full month across all enabled products. This catches both statistical and commercial surprises before a broad rollout.

7. VWO: Best for conversion-focused web experimentation

Best for

VWO is strongest for conversion-rate optimization teams that need visual editing, A/B and split-URL tests, multivariate testing, targeting, reporting, and a workflow accessible to marketers. VWO Feature Experimentation extends the platform to server-side and application changes, making it a plausible Statsig alternative when web optimization is the center of gravity.

It is a better candidate for landing pages, merchandising, signup flows, and campaign experiences than for a purely backend experimentation program. Engineering-heavy buyers should evaluate its SDK, raw data, flags, and metric model as deeply as the visual editor.

Key strengths

The VWO plans page lists A/B, split-URL, and multivariate tests, targeting and reporting options, custom events, mutual exclusion, API access, and feature-experimentation capabilities across its packages. The visual workflow is designed for creating variants without waiting for a full application release, while rollout features can send a winner to more traffic.

VWO's SmartStats reporting uses Bayesian analysis. The broader platform includes heatmaps, recordings, funnels, personalization, planning, and program-management tools depending on the package. That combination can help an optimization group move from research to hypothesis, test creation, analysis, and follow-up in one suite.

The product has a long track record in web experimentation and supports client-side, server-side, and mobile use cases. For an organization replacing Statsig because marketers could not independently run website tests, that mature web surface can outweigh deeper warehouse-native methods.

Watchouts

Visual changes still execute in the browser. Measure cumulative layout shift, script loading, flicker, consent behavior, CSP compatibility, bot filtering, SPA route changes, and the failure mode when VWO is unavailable. A visually correct test is not production-safe if it changes performance or appears before consent.

Bayesian reporting does not eliminate design obligations. Predefine the primary metric, practical effect threshold, guardrails, audience, and minimum duration. Ask how SmartStats handles multiple goals, repeated observation, segments, missing data, outliers, SRM, and ratio metrics. If warehouse metrics are required, verify the exact import and analysis path in the purchased package.

VWO has several products and tier boundaries. Confirm whether Testing, Feature Experimentation, Insights, Personalize, and Plan are separate charges, and whether raw export, APIs, SSO, mutual exclusion, advanced targeting, and support require higher tiers.

Pricing and implementation notes

VWO offers an explore-for-free route, but its public pricing page directs buyers to schedule a demo for paid Growth, Pro, and Enterprise testing packages. Obtain a quote based on monthly tested visitors, domains, workspaces, concurrent tests, server-side use, seats, raw export, integrations, support, and additional VWO products.

Run a production-shaped landing-page test and a server-side application test if both are in scope. Measure page performance, assignment consistency, exposure and conversion counts, visual-editor maintainability, raw-data access, and result reproducibility. A web-focused product should win on the complete optimization workflow, not solely on how quickly a button color can be changed.

How the seven alternatives differ in practice

Decision priorityStrongest candidatesWhat to verify
Governed warehouse metricsGrowthBook, Datadog ExperimentsSQL transparency, metric versioning, warehouse cost, backfills, access controls
Release flags plus experimentsGrowthBook, LaunchDarklySDK parity, exposure timing, kill switches, rollout transition, offline behavior
Visual website optimizationKameleoon, Optimizely, VWOEditor reliability, page speed, consent, SPA support, raw export
Broad product-data suiteGrowthBook, PostHog, DatadogIdentity model, event quality, analytics depth, total metered cost
Advanced statistical choiceGrowthBook, Datadog Experiments, Kameleoon, OptimizelyMethod applicability, documentation, stopping policy, CUPED scope, corrections
Open-source deploymentGrowthBookSupported architecture, enterprise license boundary, operating cost
Enterprise cross-functional programOptimizely, Kameleoon, GrowthBookGovernance, templates, holdouts, permissions, training, support

Evaluate the complete causal chain. A warehouse engine with unreliable exposures, an SDK paired with duplicated business metrics, or a visual editor that bypasses consent can all produce a failed experiment program.

How to migrate experiments from Statsig

Inventory the actual Statsig surface

List every gate, dynamic configuration, experiment, layer, holdout, metric, dashboard, product-analytics report, replay workflow, data export, warehouse connection, SDK, proxy, role, approval, and integration in use. Mark the owner and last activity. This prevents a team from migrating experiments while quietly breaking a feature gate or executive report.

Old results may need to remain searchable after SDK calls stop. Decide whether to migrate each record, export an immutable report, or retain time-bounded read-only access.

Freeze semantics before moving data

Export or document the randomization unit, assignment key, variant weights, targeting, namespace or layer, start and stop times, exposure definition, metric SQL or event filters, attribution windows, exclusions, capping, statistical method, correction policy, decision, and owner for each relevant experiment.

Create versioned metric specifications outside either vendor. For each metric, include an executable query or event definition plus fixtures that cover zero activity, repeat activity, late events, refunds, identity merges, and missing data. A migration is successful when both systems calculate the intended business quantity, not merely when their labels match.

Do not switch a live experiment's assignment algorithm

Different hashing functions, salts, namespaces, or bucketing ranges can reassign participants. That creates contamination: the same subject may see control under Statsig and treatment under the replacement. Even if the visible split remains 50/50, the groups are no longer the original randomized comparison.

Finish or stop active tests before changing assignment. If a critical long-running holdout cannot stop, preserve its original assignment service until the decision window closes, or migrate a durable assignment table and prove exact parity for every subject. Never concatenate results from two assignment regimes without a design reviewed by a qualified experimenter.

Shadow analysis before shadow assignment

Reanalyze a completed Statsig experiment in the candidate using the same assignment and outcome data. Compare subject counts, variant counts, exposure timestamps, exclusions, metric values, point estimates, intervals, corrections, SRM status, and conclusions. Differences are useful: they reveal semantic or methodological choices that need to be made explicit.

Next, send production assignment or exposure data to both analysis systems without changing what users receive. Only after analysis matches should the new SDK calculate decisions in shadow mode. Compare millions of representative contexts across languages and runtimes, including null attributes, semantic versions, Unicode, dates, prerequisites, and partial outages.

Run an A/A test and a bounded A/B test

An A/A test serves identical behavior under two labels. It should show the configured traffic split, low SRM incidence, stable metric baselines, and the expected rate of chance alerts under the selected method. Microsoft's SRM guidance notes that an imbalance can invalidate the experiment even when the result looks plausible; diagnose any mismatch before proceeding.

Then run a low-risk A/B test with a known hypothesis, reversible treatment, one primary metric, and operational guardrails. Pre-register the decision rule. Reproduce the result outside the UI. This is the final evidence that assignment, exposure, metric, statistics, and workflow function together.

A proof-of-concept scorecard

Score evidence, not sales claims. A useful proof of concept includes these gates:

  1. Assignment parity: The same subject receives the same variation across supported runtimes, retries, sessions, and deployments.
  2. Exposure accuracy: Only affected subjects enter the analysis, repeated evaluations do not inflate the population, and treatment cannot change inclusion improperly.
  3. Metric reconciliation: Counts and values match an independently executed query within a documented tolerance.
  4. Statistical reproducibility: Point estimates, uncertainty intervals, corrections, and quality warnings can be explained from documented methods.
  5. Data-quality response: A seeded SRM, missing event stream, delayed partition, and identity fault are detected and prevent a casual ship decision.
  6. Operational resilience: Applications behave safely when the control plane or network is unavailable, and operators can stop a harmful treatment.
  7. Governance fit: Templates, permissions, audit history, APIs, and reports support the organization's risk tiers without blocking routine work.
  8. Cost at scale: The model includes subjects, events, requests, seats, warehouse compute, retention, support, and every adjacent product activated by the workflow.
  9. Exit test: Assignments, configurations, metrics, and results can be exported in useful formats without a professional-services project.

Use one dataset and rubric for every finalist. A common test reveals which system fits the organization's actual workload.

The best Statsig alternative for experimentation

GrowthBook is the best overall alternative for product and engineering teams that want rigorous experimentation without surrendering control of their data model or deployment path. It supports a managed start, warehouse-native growth, an open-source option, flags and experiments in one workflow, and a pricing model that does not charge by experimental subject or experiment count. Teams can start with GrowthBook for free and add sequential testing, CUPED, stronger governance, or enterprise support as the program matures.

Datadog Experiments deserves a close look for data-mature Datadog customers and teams that value Eppo's statistical depth plus operational telemetry. Optimizely is the broad enterprise-suite choice. Kameleoon is compelling for a combined web and feature program. LaunchDarkly is the release-centric option. PostHog is the fast all-in-one path for small technical teams. VWO remains strong for conversion-focused web experimentation.

Decide with a replayed experiment, an A/A test, and a production-shaped proof of concept. For help with data architecture, SDK rollout, metric governance, or migration risk, book a GrowthBook demo and bring the scorecard.

Build a trustworthy test program

Start free with feature flags, A/B testing, product analytics, and a path from managed data to your own warehouse.

Start with GrowthBook

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.