Feature Flags
Experiments

Best 8 open-source alternatives to Optimizely

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

The best open source Optimizely alternative is not simply the repository with the most stars. It is the system your team can operate safely while preserving the release and measurement workflows it actually uses.

Optimizely remains a mature commercial experimentation portfolio spanning web optimization, feature experimentation, feature management, personalization, analytics, and program operations. Teams usually consider open-source alternatives for a different deployment model, more control over data, predictable pricing, an auditable evaluation engine, or the ability to connect feature delivery to warehouse metrics.

This guide compares 8 open-source options: GrowthBook, Unleash, Flagsmith, Flipt, GO Feature Flag, FeatBit, PostHog, and an OpenFeature-plus-flagd architecture. These projects solve different problems. Some are complete control planes with hosted and self-hosted editions. Some are focused flag services. OpenFeature is a vendor-neutral API specification, while flagd is a reference flag-evaluation engine; together they are building blocks rather than a turnkey Optimizely replacement.

GrowthBook is the strongest overall recommendation when product teams need both release control and trustworthy experiment analysis. Unleash is a strong feature-management specialist. Flagsmith suits teams that want flags and remote configuration. Flipt and GO Feature Flag fit GitOps and OpenFeature-oriented architectures. The right answer depends on runtime behavior, governance, measurement, and how much platform ownership your team wants.

Map the Optimizely workload before choosing a repository

An open-source flag server is not automatically an open-source replacement for Optimizely Web Experimentation. It may provide deterministic assignment and rollouts but no visual editor, browser snippet, metric analysis, or experimentation program workflow. Conversely, an analytics suite may measure tests but lack the release controls used by backend services.

Inventory active Optimizely products, snippets, SDKs, audiences, metrics, data exports, approvals, and integrations. Mark each item as web optimization, feature experiment, release flag, personalization, analytics, or program operations. Then decide whether one open-source platform should own the complete path or whether a composed stack is acceptable. That mapping prevents a free repository from becoming an expensive collection of missing systems.

Open source Optimizely alternatives at a glance

OptionBest forOpen-source roleMain watchout
GrowthBookFlags plus warehouse-native experimentationMIT-licensed core with separately licensed enterprise directoriesSelf-hosting still requires operational ownership
UnleashEnterprise-oriented feature managementAGPL-3.0-licensed flag control planeRigorous experiment analysis needs another layer
FlagsmithFlags, remote config, and flexible hostingSelf-hostable platform and SDK ecosystemCompare open-source and paid governance features carefully
FliptGitOps and infrastructure-focused teamsGPL-3.0 server with declarative workflowsSmaller product and integration surface than Optimizely
GO Feature FlagLightweight OpenFeature deploymentsMIT-licensed Go relay proxy and providerYou assemble more of the control and analytics stack
FeatBitTeams wanting an Optimizely-like interfaceMIT-licensed self-hostable platformVerify enterprise maturity and project activity for your needs
PostHogTeams consolidating product toolingMIT-licensed core with separately licensed enterprise codeSelf-hosting is officially unsupported
OpenFeature plus flagdVendor-neutral evaluation architectureApache-2.0 CNCF specification and reference implementationIt is a foundation, not a finished governance platform

Independent directories and discussions can help discover projects but should not determine the decision. An open-source alternatives directory highlights PostHog, Unleash, GrowthBook, Flagsmith, and FeatBit for different priorities. A practitioner open-source discussion shows why cost and control motivate the search. These sources reflect community perspective; verify current behavior against repositories, documentation, and a proof of concept.

What “open source alternative” should mean

Open source can describe several different arrangements:

  • The complete server and UI can be self-hosted under an OSI-approved license.
  • A core runtime is open source, while governance or enterprise features are commercial.
  • SDKs are open source, but the control plane is proprietary.
  • A specification and provider interface are open, while storage and management are assembled separately.
  • Source is visible but uses a license that restricts production or commercial use.

Read the license for the version you plan to deploy. Identify which components are required for production, including proxy, database, UI, edge service, telemetry, audit logging, and authentication. Then map which of those are available in the open-source distribution.

The Open Source Initiative definition is a useful baseline, but licensing is only one axis. Operational independence also depends on whether configuration exports cleanly, SDKs can change providers, and runtime evaluation continues safely when the control plane is unavailable.

Why teams move away from Optimizely

Deployment and data control

Some organizations require services to run inside their network or a specific cloud account. Feature configurations may reveal unreleased product strategy, customer segments, entitlements, or internal systems. Self-hosting can provide control over network paths, storage, retention, backups, and regional placement.

Control also creates responsibility. Your team owns upgrades, scaling, database health, encryption, access policies, incident response, and disaster recovery. A managed service may have a higher subscription cost and lower total operating cost.

Pricing model

Optimizely's current packaging is individually quoted across products such as Web Experimentation, Feature Experimentation, analytics, and personalization. Billing and implementation depend on traffic, purchased products, and program complexity. A browser-heavy optimization program and a backend feature-experimentation program can therefore have very different cost and staffing profiles.

Open-source alternatives may use per-seat cloud pricing, requests, events, or infrastructure you operate. Build a 12- to 24-month model using actual application topology and traffic. “Free self-hosting” is not a cost model.

Experimentation architecture

Feature management and experimentation overlap, but they are not the same. A flag can assign variants; a controlled experiment also needs exposure logging, metrics, attribution windows, quality checks, uncertainty estimates, and a decision rule.

GrowthBook's feature flag experiments connect assignment and analysis, while its warehouse-native platform queries metrics from existing data sources. That model differs from tools that require teams to send behavioral events into a vendor platform or build the analysis separately.

Portability and auditability

Open source lets engineers inspect evaluation behavior and, in some cases, change it. That can be important for deterministic bucketing, privacy, latency, and incident analysis. A standard interface such as OpenFeature can reduce application-level coupling to one provider.

Portability is never automatic. Targeting rules, prerequisites, multivariate values, segment behavior, hashing, and event semantics differ across platforms. A provider abstraction cannot make incompatible configurations identical.

How to evaluate an open-source flag platform

Start with runtime failure behavior

The first question is not whether the dashboard looks good. It is what the application does when the flag system fails.

Test:

  • Fresh startup without the control plane.
  • Loss of network after configuration has loaded.
  • Expired or corrupt cache.
  • Slow initialization.
  • Malformed attribute values.
  • Evaluation errors and fallback behavior.
  • Multiple application replicas receiving updates.
  • Configuration rollback.

Local evaluation can keep runtime calls fast and resilient after a configuration payload is available. Proxy or remote evaluation can centralize logic and protect sensitive rules. Both can be reliable when designed and operated correctly; understand the dependency graph.

Reproduce targeting semantics

Create a fixture that covers booleans, strings, numbers, JSON values, percentage rollouts, segments, prerequisites, null attributes, semantic versions, dates, and multi-context users. Run it through both the current and candidate SDKs.

Do not assume “percentage rollout” preserves the same users. Providers use different hashing inputs and algorithms. If a migration changes assignments during an active experiment, the result can be contaminated. Either preserve bucketing explicitly or finish the experiment before switching.

Separate flag governance from code cleanup

Permissions, approvals, audit logs, environments, projects, and change histories matter in the control plane. Flag debt lives in code. A platform can mark a flag stale without safely deleting its conditional branches.

Define ownership, expected lifetime, cleanup issue, and removal criteria when the flag is created. Use code references and static analysis where available, but require engineering review before deleting behavior.

Test experiment readiness

If the team uses flags for experiments, require:

  • Stable assignment at the correct unit.
  • Exposure logging at the moment treatment affects behavior.
  • Mutual exclusion or interaction management.
  • Sample ratio mismatch detection.
  • Guardrails and metric governance.
  • Frequentist or Bayesian methods appropriate to policy.
  • Sequential or fixed-horizon stopping rules.
  • Inspectable queries and event joins.

A 50/50 rollout without this layer can reduce release risk, but it does not by itself support a trustworthy causal claim.

1. GrowthBook: Best overall open-source alternative

Best for

GrowthBook is best for engineering, product, and data teams that want feature flags, progressive delivery, warehouse-native experimentation, and product analytics in one open-source platform.

Key strengths

GrowthBook feature flags support targeting, percentage rollouts, remote configuration values, prerequisites, environments, webhooks, APIs, and SDKs across common client and server stacks. Evaluation happens locally in SDKs after configuration is loaded, avoiding a network call for each decision.

The differentiator is what happens after release. Teams can turn a flag rule into an experiment and analyze outcomes using governed metrics in their own warehouse. GrowthBook supports Bayesian and frequentist analysis, sequential testing, CUPED, guardrails, dimensions, holdouts, bandits, and sample ratio mismatch checks.

The GrowthBook GitHub license places code outside named enterprise directories under the MIT Expat license, while those enterprise directories have a separate GrowthBook Enterprise License. Cloud and self-hosted options use the same product foundation, which gives teams a practical managed starting point and a credible self-hosting path.

Watchouts

Self-hosting transfers availability, upgrades, backups, observability, and security to your team. The experimentation layer is most valuable when the organization has reliable event or warehouse data. Teams that only need a small set of simple toggles may find a narrower service easier to operate.

Pricing and implementation notes

GrowthBook publishes a free Starter cloud plan for up to 3 users, a per-seat Pro plan, custom Enterprise packaging, and a free self-hosted option. Experiments, flags, and traffic are unlimited on the published plans. Test one backend flag, one client flag, one JSON configuration, and one experiment using a trusted metric.

If you want to replace Optimizely without separating feature delivery from measurement, start with GrowthBook for free. Larger teams can book a demo to review migration, deployment, and governance.

2. Unleash: Best for feature-management specialists

Best for

Unleash fits platform and engineering teams that want a mature open-source feature-management control plane, flexible self-hosting, and enterprise governance without requiring built-in product experimentation.

Key strengths

Unleash provides an open-source control plane with activation strategies, variants, constraints, segments, environments, projects, and SDKs. The current Unleash repository license is AGPL-3.0, so legal review should replace assumptions based on older Apache-2.0 descriptions. Its client SDK architecture emphasizes local evaluation using synchronized configuration.

The platform has a clear feature-management focus. Commercial editions add managed hosting and enterprise capabilities, while the open-source project gives teams a substantial self-hosted foundation. Unleash also participates in the OpenFeature ecosystem, which can support a more portable application interface.

Watchouts

Variants and impression data are not a complete experimentation analysis system. Teams that need causal product decisions will usually connect external analytics or an experimentation platform. Compare which governance, lifecycle, and collaboration features belong to open source versus commercial plans.

Pricing and implementation notes

Self-hosted open source has no subscription fee, but AGPL obligations still matter and managed or enterprise plans use paid packaging. Size the database, cache, edge/proxy components, and update traffic. In a proof of concept, test constraint semantics and configuration propagation across multiple services.

GrowthBook vs Optimizely

Review feature flag architecture, experimentation depth, platform flexibility, and cost before treating open source as the only decision criterion.

Compare GrowthBook and Optimizely

3. Flagsmith: Best for flags and remote configuration

Best for

Flagsmith is a good fit for teams that need feature flags, dynamic configuration, segments, identities, and cloud or self-hosted deployment.

Key strengths

Flagsmith's repository contains the API, dashboard, and core platform under a BSD-3-Clause license. Its data model supports boolean flags and remote configuration values, which is useful for controlling limits, copy, endpoints, model settings, or other behavior without deployment.

The product offers client and server SDKs, identity-based targeting, multivariate values, webhooks, and integrations. Teams can choose hosted, private cloud, or self-hosted arrangements depending on commercial requirements.

Watchouts

Review the boundary between the open-source distribution and paid enterprise capabilities such as advanced governance and support. A/B or multivariate allocation still needs trustworthy exposure data and statistical analysis; do not treat a variant report as equivalent to a mature experiment platform.

Pricing and implementation notes

Flagsmith publishes a free hosted tier and paid cloud and enterprise plans. Self-hosters should model database, cache, deployment, and upgrade ownership. Test identity traits, multivariate values, offline behavior, and import/export before committing.

4. Flipt: Best for GitOps workflows

Best for

Flipt fits infrastructure-oriented teams that want self-hosted feature flags, declarative configuration, Git-based change workflows, and a relatively focused operational footprint.

Key strengths

Flipt's repository provides a GPL-3.0 flag service designed around developer and operations workflows. Teams can manage configuration declaratively, review changes through Git, and integrate the system with OpenFeature providers. Review the server and SDK licenses separately when embedding components or distributing modified builds.

Git-backed configuration can make review, rollback, and environment promotion familiar. It also creates a durable history outside a proprietary dashboard. The focused scope is attractive when teams do not want a larger analytics suite.

Watchouts

A Git workflow is not automatically safe for urgent production changes. Validate propagation speed, conflict behavior, emergency access, secrets, and auditability. Flipt also has a smaller enterprise and experimentation surface than Optimizely, so teams may need to assemble analytics and governance around it.

Pricing and implementation notes

The open-source edition is self-hosted, with commercial offerings for teams that want additional management or support. Test Git reconciliation, SDK caching, evaluation consistency, and rollback under load.

5. GO Feature Flag: Best lightweight OpenFeature option

Best for

GO Feature Flag suits teams that want a lightweight, open-source flag system centered on OpenFeature, external configuration storage, and a relay proxy.

Key strengths

The MIT-licensed GO Feature Flag repository supports multiple configuration retrievers and exporters, percentage rollouts, targeting, scheduled changes, and provider integrations. The relay proxy can centralize evaluation and expose a standardized interface to applications.

This modularity is useful for teams comfortable assembling infrastructure. Configuration can live in Git, object storage, or another supported source, while telemetry can be exported for analysis.

Watchouts

GO Feature Flag is not a full replacement for Optimizely's enterprise dashboard, approvals, integrations, and experimentation. A small platform team may appreciate the control; an application team without operational capacity may spend more time building management workflows than expected.

Pricing and implementation notes

There is no software subscription for the open-source project. Budget for the relay, configuration store, monitoring, deployment, and support. Test concurrent updates, cache behavior, provider compatibility, and failure defaults.

6. FeatBit: Best for a familiar all-in-one interface

Best for

FeatBit is worth evaluating for teams that want a self-hosted platform with feature flags, targeting, progressive rollouts, and experimentation concepts in an interface closer to commercial feature-management products.

Key strengths

The MIT-licensed FeatBit repository includes a self-hosted control plane and SDK ecosystem. It supports segments, percentage rollouts, variations, webhooks, and streaming configuration updates. The project can give smaller teams a more packaged starting point than assembling a provider and store from primitives.

Watchouts

Project maturity matters more than feature screenshots. Inspect recent releases, contributor concentration, security processes, upgrade instructions, documentation depth, and response to issues. Verify how experiment analysis works and whether it meets the statistical standard your data team expects.

Pricing and implementation notes

Open-source deployment avoids a core license fee; commercial services may be available. Run a failure test, upgrade test, backup restore, and SDK compatibility matrix before production use.

7. PostHog: Best for product-stack consolidation

Best for

PostHog fits startups and product teams that want feature flags alongside product analytics, session replay, experiments, surveys, data pipelines, and other product tooling.

Key strengths

PostHog feature flags support boolean and multivariate flags, person or group properties, percentage rollout, payloads, and experiments. The same event platform can diagnose behavior around a rollout, which reduces integration work for teams already using PostHog.

The PostHog repository license puts code outside its enterprise directory under the MIT Expat license. That makes it relevant to open-source buyers, while the hosted product provides usage-based pricing and free allowances. The suite can replace several vendors when the organization prefers one product data system.

Watchouts

PostHog explicitly describes self-hosted deployments as officially unsupported, provides no paid support or guarantees for them, and keeps paid-plan features cloud-only. Its free Docker Compose path is better treated as a hobby or internally owned deployment than a supported production alternative. The cloud suite also spans several usage meters, and advanced experiment teams should test its methodology against their decision policy.

Pricing and implementation notes

Cloud pricing is usage based after free allowances; the published free plan includes one project, one-year retention, and unlimited members. Estimate analytics events, replay, feature-flag requests, data pipelines, and add-ons together. In a trial, confirm identity behavior and reconcile experiment metrics with a trusted source.

8. OpenFeature plus flagd: Best for vendor-neutral foundations

Best for

This architecture fits platform teams that want a standardized application API and are prepared to build or choose the surrounding management, storage, and governance components.

Key strengths

OpenFeature is an Apache-2.0-licensed CNCF incubating project that defines vendor-neutral feature flag APIs and concepts. Applications use an OpenFeature SDK and provider rather than a vendor-specific evaluation API. The Apache-2.0 flagd project is a reference implementation that evaluates declarative flag configurations and integrates with OpenFeature providers.

This separation can reduce code coupling and support provider changes or multi-provider architectures. It also gives platform teams control over where evaluation runs and how configuration is distributed.

Watchouts

OpenFeature is not a control plane, and flagd is not a complete Optimizely replacement. You still need authoring, approvals, storage, distribution, audit logs, secrets, environment promotion, observability, lifecycle management, and experimentation analysis.

Pricing and implementation notes

The projects are open source, but the platform you assemble has engineering and operational cost. Use this option when feature management is a strategic internal platform capability, not merely a way to avoid a subscription.

Architecture choices that determine reliability

Two platforms can support the same targeting rule and behave very differently in production. Evaluate the data path from a flag edit to an application decision.

Local evaluation

With local evaluation, an SDK downloads a configuration payload and calculates the variation inside the application process. This can provide low decision latency and lets the application continue with the last known configuration during a temporary control-plane outage.

The tradeoff is configuration distribution. Every relevant process needs a fresh, valid payload. Large segments or complex rules can increase payload size, and client-side SDKs must not receive sensitive targeting logic or attributes. Confirm whether the platform generates a client-safe subset of configuration.

Test cold start separately from steady state. An application that starts before configuration is available should use an explicit fallback, block readiness, or load a durable cache according to the risk of the flag. A payment permission and a cosmetic button color should not necessarily share the same failure policy.

Remote evaluation

Remote evaluation sends context to a service that returns the variation. Rules stay centralized, sensitive logic can remain server-side, and configuration can change without distributing a large payload to every application.

The service becomes a runtime dependency. Measure p50, p95, and p99 latency; connection pool behavior; retry amplification; regional failure; and capacity during deploys. Add a local cache or sidecar if the architecture supports it, and define what happens when the remote evaluator is slow rather than completely unavailable.

Remote evaluation also transmits attributes. Minimize payloads, classify personal data, and verify logs and traces do not retain sensitive context unexpectedly.

Relay proxies and edge components

Many systems use a relay, proxy, or edge service between the control plane and SDKs. This can reduce outbound connections, keep evaluation traffic inside a network, centralize caches, or distribute configuration across regions.

Treat the component as production infrastructure. Define horizontal scaling, readiness, health checks, version compatibility, certificate rotation, and disaster recovery. A proxy that exists only in an architecture diagram can become a single point of failure.

Streaming versus polling

Streaming delivers changes quickly and can support emergency kill switches. Polling is simpler and can be easier to operate through restrictive networks. The relevant metric is not protocol preference; it is the maximum safe delay between approval and consistent application behavior.

Test dropped connections, reconnect storms, out-of-order updates, and a rollback performed during network disruption. Record configuration versions in application telemetry so an incident responder can identify which version a service actually evaluated.

Security and governance requirements

Feature flag systems control production behavior, which makes them part of the software supply chain and authorization boundary.

Authentication and least privilege

Require SSO for people and short-lived or rotatable credentials for services. Separate read-only SDK keys from administration credentials. Scope tokens to the minimum project and environment, and prevent a client-side key from reading server-only configuration.

Create roles around actions: view, create draft, approve, change production, manage credentials, and administer the platform. A role called “developer” is too vague when one action can expose all customers to unreleased code.

Change control

Every production change should record the actor, timestamp, previous value, new value, reason, and approval. Important flags may need separation of duties so the person proposing a change cannot approve it alone.

Test the audit log rather than checking a procurement box. Change a targeting rule, segment, prerequisite, secret, and environment setting. Confirm the log captures the effective behavior and can be exported to your security system.

Secrets and sensitive configuration

Feature flags are not a secret manager. A JSON payload may be convenient for endpoints or UI text, but it should not distribute database passwords, private keys, or unrestricted API tokens. Client-side configuration is inspectable by the user.

Define an allowed-data policy and scan configuration where practical. If remote config controls model names, pricing tiers, or customer entitlements, apply the same review discipline as code.

Network and data boundaries

Document which components communicate with the public internet, what context SDKs send, which fields are logged, and where backups reside. Self-hosting a UI does not guarantee that telemetry, package downloads, support bundles, or analytics remain inside the boundary.

Validate outbound dependencies in an isolated environment. Review containers, package provenance, default telemetry, and update channels. Pin versions and use vulnerability scanning consistent with the rest of your infrastructure.

Backups and recovery

A flag database contains current production policy. Losing it can be as disruptive as losing application configuration. Define recovery point and recovery time objectives, encrypt backups, and test restoration.

Also preserve a configuration export in a durable, reviewable format. A database backup helps disaster recovery; a human-readable export helps migration, audit, and incident diagnosis.

Total cost of ownership

Build a cost model with four columns rather than comparing only subscription fees.

Software and infrastructure

Include managed-plan fees or the compute, database, cache, storage, load balancer, observability, backup, and network cost of self-hosting. Model separate regions and environments if production requires them.

Platform engineering

Estimate initial deployment, upgrades, dependency changes, security patches, capacity planning, and on-call response. A few hours per month can exceed the subscription difference for a small company; for a large regulated enterprise, internal control may justify substantially more work.

Migration and application work

Count SDK changes, rule translation, test fixtures, identity cleanup, dual running, documentation, training, and flag cleanup. A provider abstraction can reduce future application changes, but it does not eliminate the first migration.

Missing-product cost

If the open-source option lacks approvals, code references, experimentation, analytics, or support, estimate the cost of buying or building those capabilities. The cheapest flag server can become the most expensive platform when teams reconstruct a control plane around it.

Model at least three years. Include team and traffic growth, and assign owners to operational work. The output should make the trade clear: what the company pays a vendor to own, what it chooses to own internally, and which risks remain.

Run the model with an optimistic and a stressed case. The stressed case should include a regional deployment, twice the expected service count, a security patch outside normal hours, one failed upgrade, and a data-restoration exercise. That scenario is not a prediction; it reveals whether the apparent savings depend on everything going right. Assign a financial value to engineering time and incident risk so “free” infrastructure is evaluated on the same basis as a vendor contract over a realistic planning horizon.

Migration plan from Optimizely

Inventory before translating

Export flags, variations, projects, environments, segments, prerequisites, tags, owners, and change history. Scan repositories for SDK initialization, flag keys, fallbacks, event hooks, and test fixtures. Classify flags as active release, experiment, permission, operational, configuration, or stale.

Delete confirmed stale flags before migration. Rebuilding debt in a new system creates risk without value.

Map semantics explicitly

Create a mapping document for:

  • Context and identity attributes.
  • Targeting operators.
  • Missing and null values.
  • Segment membership.
  • Prerequisite behavior.
  • Percentage bucketing.
  • JSON and typed values.
  • Offline and initialization fallbacks.
  • Exposure or impression events.
  • Environment and project boundaries.

Where behavior cannot be preserved, document the change and identify affected flags.

Build a dual-evaluation harness

For a representative fixture of identities and attributes, evaluate both systems and compare results. Include edge cases and randomized rollout buckets. Run the harness in CI while migrating rules.

Shadow evaluation can compare production decisions without letting the candidate control behavior. Do not send sensitive attributes to a second system without privacy review.

Migrate in risk order

Start with dormant or internal flags, then low-risk configuration, then ordinary release flags. Move permissions, billing, safety controls, and active experiments last. Freeze rule changes during each cutover window or synchronize them through a defined process.

Preserve the old SDK and configuration as a rollback path until error rates, evaluation parity, and update propagation meet the agreed threshold.

Proof-of-concept scorecard

Give every finalist the same workload:

  • 3 SDK languages representing actual services and clients.
  • 25 flags across boolean, string, number, and JSON values.
  • Nested segments and prerequisites.
  • A gradual rollout to 1%, 10%, 50%, and 100%.
  • One account-level experiment and one user-level experiment.
  • 3 environments and at least 2 projects.
  • A control-plane outage and cold-start test.
  • A configuration rollback.
  • SSO, RBAC, audit, and export requirements.
  • Projected service topology and client traffic.

Score runtime correctness, update latency, offline behavior, developer experience, governance, experiment evidence, operational burden, portability, and total cost. Require the internal operator—not the vendor—to restore a backup, rotate a secret, upgrade the platform, and diagnose a failed evaluation.

When Optimizely is still the right answer

Open source is not automatically better. Optimizely may remain the strongest fit when a company needs its breadth of SDKs, mature approvals, integrations, release observability, enterprise support, or governance capabilities and prefers a managed service.

Staying can also be rational when migration risk exceeds the benefit. A large flag estate with complex targeting, active experiments, and many application teams requires careful coordination. Negotiate packaging, improve flag cleanup, and reduce unnecessary service connections before assuming replacement is the only cost lever.

The decision should compare the current platform with the full future operating model—not a subscription invoice with a repository license.

Final recommendation

Choose GrowthBook when you want the most complete open-source alternative for feature flags and controlled experimentation. Choose Unleash for feature-management depth without a built-in experimentation requirement. Choose Flagsmith for flags and remote configuration across flexible hosting models. Choose Flipt for GitOps, GO Feature Flag for a lightweight OpenFeature stack, and FeatBit for a packaged self-hosted interface. Choose PostHog when product-tool consolidation is the goal. Build on OpenFeature and flagd when your platform team wants standardized primitives and accepts the assembly work.

For most product and engineering teams leaving Optimizely, GrowthBook provides the best balance of runtime control, transparent pricing, deployment choice, and measurement. It avoids the common migration mistake of replacing a sophisticated flag platform with toggles that cannot explain whether a release improved the product.

Start with GrowthBook for free and migrate one representative flag. If you need help mapping a larger Optimizely estate, book a GrowthBook demo.

Plan your open-source flag stack

Learn how to manage flag ownership, evaluation architecture, lifecycle debt, observability, and progressive delivery as usage scales.

Plan for Feature Flag Scale

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.