How to create feature flags with Codex

Codex can write the flag code. It should not decide the release policy by itself.
A feature flag is a production control, not a decorative wrapper around a diff. When an AI coding tool creates the change, the flag needs a clear owner, a safe default, a rollout rule, and a removal plan before anyone treats the generated code as ready to ship.
This guide shows how to use Codex to create a feature flag without turning an AI-generated patch into an unmanaged production branch. The workflow uses GrowthBook as the control plane, keeps the current exporter state unchanged, and treats the AI tool as an implementation assistant rather than the release authority.
What you are actually creating
The useful output is not just a conditional statement. It is a small release system:
- A flag key with a stable naming convention.
- A default value that returns users to the known-good experience.
- SDK code that evaluates the flag in the right runtime.
- A GrowthBook flag that product, engineering, and data teams can inspect.
- A rollout or experiment rule that controls who sees the change.
- Tests that prove both the control and treatment paths still work.
That distinction matters because Codex is strongest for terminal-first work where the agent reads a repository, edits files, runs commands, and can be used interactively or through non-interactive execution. Codex can automate a full local workflow, which makes approval boundaries, sandboxing, tests, and rollout scope part of the release design rather than an afterthought.
The implementation details below are grounded in OpenAI's Codex manual, Codex CLI docs, Codex MCP docs, Codex slash command docs, Model Context Protocol introduction, and developer discussions about feature flag organization. For GrowthBook-specific steps, use the GrowthBook MCP docs, feature flag docs, and feature flag experiment docs.
Start by defining the flag before writing code
Ask Codex to help you create a flag spec before it edits the repository. The spec should answer five questions:
If the agent cannot answer those questions, the task is not ready for implementation. It is still in product design.
For a normal UI or API change, use a boolean flag. For AI behavior, prompts, model parameters, or ranking configuration, use a JSON flag when the runtime needs structured values. GrowthBook's feature flag product page and feature flag docs cover the control patterns, while the AI-native development page explains why these controls matter more as agents write more of the code.
Connect GrowthBook to the AI workflow
The fastest path is to give the agent a real GrowthBook tool rather than asking it to invent dashboard steps from memory. GrowthBook's MCP Server exposes tools for creating flags, listing flags, creating force rules, generating flag types, creating experiments, reading metrics, and searching the docs.
Codex stores MCP configuration in config.toml and also supports codex mcp commands, so teams can manage GrowthBook access from the CLI or project config.
For a cloud GrowthBook instance, the core setup values are:
GB_API_KEY=YOUR_API_KEY
GB_EMAIL=YOUR_EMAIL
Self-hosted or proxied environments can also set GB_API_URL, GB_APP_ORIGIN, and custom GB_HTTP_HEADER_* values. That matters for teams that protect GrowthBook behind a reverse proxy or private access layer.
Once the server is connected, use a prompt with constraints, not a vague request:
Create a GrowthBook boolean feature flag named new_checkout_summary.
Default it to false.
Wrap the checkout summary component with the flag.
Keep the current checkout path as the fallback.
Add tests for both flag states.
Do not change pricing, payment, or authentication logic.
Return the GrowthBook flag URL and the files changed.
The MCP server can create the flag and return a direct link, but the human still decides whether the targeting rule is appropriate for production.
Ask Codex to make a narrow implementation
The safest prompt names the files, the runtime, and the boundary. If your application already uses a GrowthBook SDK, tell the agent to reuse the existing client. If it does not, ask it to inspect the GrowthBook SDK docs and propose the smallest integration path first.
For a React feature, the shape usually looks like this:
const showNewSummary = useFeatureIsOn("new_checkout_summary");
return showNewSummary ? (
<NewCheckoutSummary order={order} />
) : (
<CurrentCheckoutSummary order={order} />
);
That code is intentionally boring. The fallback is visible. The flag key is stable. Both branches can be tested.
For server-side logic, keep the fallback equally explicit:
const useNewRouting = growthbook.isOn("new_pricing_router");
const result = useNewRouting
? routeWithNewPricingRules(account)
: routeWithCurrentPricingRules(account);
Do not let the agent hide the old path while the rollout is still active. If the control path disappears, the feature flag becomes a one-way migration switch rather than a reversible release control.
Create a rollout rule only after the code is reviewable
Once the branch compiles and tests pass, move from code generation to rollout design. GrowthBook supports targeted releases, force rules, percentage rollouts, and feature flag experiments. The right first rule depends on risk:
- Use an internal force rule when the feature needs staff-only validation.
- Use a beta-user rule when the audience has opted into early access.
- Use a percentage rollout when the change is low risk and operationally easy to reverse.
- Use a feature flag experiment when the team needs a metric-backed decision.
The key is to separate deployment from exposure. The code can reach production with the flag defaulted off. Exposure can then move through GrowthBook rules after review.
For generated code, this separation is the point. Codex can accelerate implementation, but GrowthBook controls release timing, targeting, fallback behavior, and measurement.
QA both paths before launch
AI-generated flag code often fails in the boring places: missing imports, wrong flag keys, untested fallback paths, or a treatment branch that assumes data the control branch never needed.
Run QA as a two-state checklist:
Ask Codex to generate tests for both states, but do not ask it to mark the release safe. A safer prompt is:
Review this feature-flagged change.
Check both flag states.
Look for missing fallback behavior, stale imports, untested branches, and user data assumptions.
Return findings by severity.
Do not modify files unless asked.
That keeps the AI in reviewer mode and makes the human decision explicit.
Turn the flag into an experiment when the decision needs evidence
Not every flag needs an A/B test. A bug-risky rollout may only need gradual exposure and monitoring. But if the team is debating whether the new behavior is better, use GrowthBook's feature flag experiments workflow.
The experiment should be designed before broad rollout:
- State the hypothesis in product terms.
- Pick one primary metric.
- Add guardrails for latency, errors, churn, or downstream conversion.
- Confirm assignment is stable.
- Decide what result will trigger ship, rollback, or iteration.
This is where GrowthBook's experimentation platform changes the AI workflow. The agent can help implement the feature, but the experiment tells the team whether the feature improved the product.
Keep cleanup in the original prompt
Feature flags are temporary unless they are permanent configuration. Ask Codex to add a cleanup note while creating the flag, not six months later when nobody remembers why it exists.
Good cleanup instructions are concrete:
- Add the flag key to the ticket or pull request.
- Name the owner.
- State the expected decision date.
- Link the GrowthBook flag.
- Include the files that should be simplified after rollout.
GrowthBook's MCP tools can also check stale flags and return cleanup guidance. That makes cleanup a first-class agent workflow rather than a manual archaeology project.
Where GrowthBook fits
Codex is useful because it can move quickly through code. GrowthBook is useful because it slows down the right part: production exposure. That pairing is the difference between AI-assisted coding and AI-assisted shipping.
Use Codex to inspect the codebase, add the SDK call, write tests, and summarize the diff. Use GrowthBook to create the flag, target the right users, run the rollout, connect the change to trusted metrics, and decide whether the feature should ship.
If your team is already using Codex, start with one small feature behind one GrowthBook flag. Keep the fallback real. Keep the rollout narrow. Then turn it into an experiment only when the decision requires evidence.
Prompt patterns that keep Codex scoped
The safest prompts are specific about files, flag behavior, and what the agent must not do. A prompt like "add a feature flag" is too open-ended because the agent has to infer the flag name, fallback behavior, SDK pattern, and rollout policy. A better prompt makes those decisions explicit.
Use this structure:
- Name the user-facing behavior.
- Name the GrowthBook flag key.
- State the default value.
- State the fallback path.
- Name files or directories to inspect first.
- Require tests for both states.
- Require a changed-file summary.
- Prohibit production exposure changes.
Example:
Inspect the checkout summary component and existing GrowthBook SDK usage.
Create or use a GrowthBook boolean flag named new_checkout_summary.
Default it to false.
Keep the current checkout summary as the fallback.
Add the new treatment in the smallest reasonable component boundary.
Add tests for flag off and flag on.
Do not change pricing, auth, payment, or production targeting rules.
Return the flag URL, files changed, and any assumptions.
The "any assumptions" line is important. It gives Codex a place to surface uncertainty instead of encoding uncertainty into code.
Common failure modes to review
AI-generated feature flag changes usually fail in predictable ways:
- The flag key in code does not match the key in GrowthBook.
- The default value is unsafe.
- The old path is removed too early.
- Analytics events fire only for the treatment.
- Tests cover the happy treatment path but not the fallback.
- The agent touches unrelated files while trying to simplify the code.
- The rollout rule is too broad for the risk of the change.
Ask the agent to review those issues after the first implementation pass. This is a better use of AI than asking it to keep coding until the diff looks impressive.
Review the feature flag implementation for release risk.
Check flag key consistency, fallback behavior, analytics parity, tests, and unrelated edits.
Report findings by severity.
Do not modify files.
Permissions and secrets
Do not give an AI coding tool a broad admin token because it is convenient. The GrowthBook API key or personal access token should match the work the agent needs to do. A read-only inspection task should not have write access. A feature-creation task should not have permission to change every project and environment if a narrower scope is available.
For local MCP setup, keep secrets out of the repository. Prefer user-level configuration, environment variables, or a secrets manager. If a team uses project-level MCP configuration, commit only the server shape and document which environment variables must be present locally.
This matters because MCP makes the agent operational. It is no longer only suggesting code. It may be able to create flags, update rules, or read experiment metadata. Treat that as production tooling.
Pull request checklist
Before merging an AI-assisted flag change, require the pull request to answer:
- What GrowthBook flag controls the change?
- What is the fallback value?
- Who owns the rollout?
- What users see the treatment first?
- What metric or signal will decide whether the feature ships?
- What tests prove flag-off and flag-on behavior?
- When should the flag be cleaned up?
The checklist should live with the PR because the PR is where reviewers already evaluate ownership. The GrowthBook flag URL gives reviewers a direct path to targeting, rules, and experiment setup.
The first proof of concept
The best first project is not the riskiest feature in the roadmap. Pick a small user-facing change with a real fallback and one measurable outcome. Create the flag, wrap the code, test both states, expose it internally, and then run a limited rollout or feature flag experiment.
That first proof of concept teaches the team how Codex, GrowthBook MCP, SDK code, tests, and review fit together. Once the loop works, encode the pattern in team instructions so every future AI-assisted feature starts with the same release discipline.
Related Articles
Ready to ship faster?
No credit card required. Start with feature flags, experimentation, and product analytics—free.

