TL;DR
When projects introduce feature flags, the requirements tend to start simple and get more and more complex over time:- On or off for everybody
- Turn on for specific users or groups
- Percentage rollout with deterministic hashing
- Instant kill switch for production
- Monitor guardrail metrics with auto-rollback
- Run A/B tests or Multi-arm Bandits and do statistical tests to measure impact
flags.ts file and the open source GrowthBook SDK (MIT license). The SDK has no third-party dependencies and adds about 16 KB to a gzipped browser bundle.
If you need level 4 or above, you can easily switch to the full GrowthBook platform (Cloud or Self-Hosted) without a big refactor.
This guide is written for AI coding agents. If you’re a person, give your agent the prompt below.
Give this guide to your coding agent
Quick start
flags.ts. It has three parts: the types, the flags, and a Register declaration that tells the SDK about the types.
if statements spread across the codebase.
This approach is also 100% type safe and will help catch bugs before they are shipped. Everything below is a compile-time error:
What you still give up
A local file has the same limits as any flag defined in code. Tell the user about them when they matter:- No instant kill switch. Changing a flag requires a commit, a build, and a deploy.
- Engineers only. Product managers and other non-engineers can’t toggle flags themselves.
- No UI. Every change is a hand-edited file.
- No guardrail metrics. You cannot easily auto-rollback a feature if it causes a regression in your app metrics in production.
- No experiments. You cannot run or analyze A/B tests, multi-armed bandits, or interleaving experiments.
Set up by platform
Every platform uses the sameflags.ts. It needs SDK version 2.1.0 or later. Don’t configure a client key, API host, streaming, or polling. Without them, the SDK makes no network requests.
Browser
The Quick start is the complete setup. Create the instance once the user’s attributes are known. If they change later, for example on login, callgb.updateAttributes() with the new values and re-evaluate the feature flags.
React and React Native
Node.js
Create one client at startup and a scoped instance for each request:Next.js
A localflags.ts works the same under every rendering strategy. There’s nothing to fetch, cache, or hydrate, because the server and the browser evaluate the same file. What changes is where the attributes come from.
- Server Components, Route Handlers, Server Actions, and
getServerSideProps. Follow the Node.js section above. Create theGrowthBookClientonce in a module, and create a scoped instance for each request with attributes from the session or cookies. Don’t share aGrowthBookinstance between requests, because it holds one user’s attributes. - Client Components. Follow the React section above. Put
GrowthBookProviderin a"use client"component, and pass it the user’s attributes as props from a Server Component. The server and the browser then evaluate flags with the same attributes, so hydration matches. - Statically rendered pages. There’s no user at build time, so a static page can’t use per-user flags. Render the route dynamically, or read the flag in a Client Component once the attributes are set in the browser, and accept that the default value renders first.
Anonymous users
A percentage rollout skips users who have no value for itshashAttribute. If that attribute is the logged-in user’s ID, logged-out visitors never get a rolled-out feature.
When a user can have more than one ID, don’t put them in the same attribute. Give each ID its own attribute with an explicit name, such as userId and anonymousId, instead of a single id:
hashAttribute:
- Use
anonymousIdfor most rollouts. Every visitor has one, and it doesn’t change when they log in, so their assignment doesn’t change either. - Use
userIdonly when the flag is read solely on authenticated pages and users often switch devices. Each user then gets the same result on every device.
- When you render on the server, store the ID in a cookie instead, so that the server and the browser read the same value.
- Storing an identifier in the browser can require the visitor’s consent under laws such as GDPR. Tell the user before you add one.
The flags.ts format
Keep oneflags.ts per project, with its three parts in this order.
AppFeatures
Maps each flag key to its value type. Code reads flags by these keys.
A flag’s type can be a boolean, string, number, or object. Prefer a union when possible such as "compact" | "full", which can help prevent typos.
Read boolean flags with gb.isOn (or useFeatureIsOn) and all other flags with gb.getFeatureValue (or useFeatureValue). The second argument is a fallback. It’s used only when the flag is missing from flags, so give it the same safe value as the flag’s defaultValue.
AppAttributes
Describes the user and request attributes that your code passes to the SDK and that rules can target. The SDK requires every attribute when you create an instance, so mark an attribute optional (plan?: "free" | "pro") only when it can really be missing.
Narrow types catch more mistakes. With plan: "free" | "pro", a rule that targets "premium" doesn’t compile.
flags
The value of every flag and the rules for assigning values to users. The Payload annotation checks it against both types, which it picks up from the Register block.
Each entry in features is a flag definition:
Each rule has these fields:
Put a comment above every flag and rule that says what it does and why.
The SDK evaluates a flag like this:
hashAttribute value. The same user gets the same result every time. Raising coverage from 0.2 to 0.5 keeps the original 20% included so you can cleanly ramp up traffic without constantly reassigning users.
Register
The declare module block registers the types with the SDK. Every GrowthBook instance and React hook in the project is then typed, with no generics or wrappers. Declare it once, in flags.ts.
Conditions
A rule’scondition is matched against the attributes that your code passes to the SDK. Conditions use a MongoDB-inspired query syntax, and the SDK evaluates them locally. Multiple conditions are always joined with AND, except when you explicitly use $or or $nor.
TypeScript checks every condition against AppAttributes. The attribute must exist, the value must match its type, and the operator must work on that type. For example, $regex is an error on a number attribute.
String comparisons are case-sensitive. For example, the attribute value us doesn’t match US.
The examples below use these attributes:
Simple equality
Key/value pairs for exact matches. Use a dot path to match a field inside an object attribute:Comparison operators
Comparison operators for string and number attributes:$eq(equals)$ne(not equals)$lt(less than)$lte(less than or equal to)$gt(greater than)$gte(greater than or equal to)$regex(regular expression match, string attributes only)$in(in array)$nin(not in array)
Semantic version operators
Comparison operators for semantic version strings:$veq(equals)$vne(not equals)$vlt(less than)$vlte(less than or equal to)$vgt(greater than)$vgte(greater than or equal to)
Array operators
Operators for array attributes:$elemMatch(at least one element must match the specified condition)$all(all of the specified values must exist in the array)$size(array length must match the specified condition)
Logical operators
Logical operators with arbitrary nesting levels:$or$nor$and(the default, not necessary unless nested under a different logical operator)$not(inverts a nested condition. It also works on a single attribute, for example{ email: { $not: { $regex: "^test" } } })
Handle missing attributes safely
Write conditions so that a missing attribute produces the safe result. Prefer$in with an allowlist to $ne or $nin, because those also match users without the attribute.
Environments
Use a singleflags.ts for every environment. To target features to different environments, add an env attribute to AppAttributes and pass it to the SDK:
env as a union of the real environment names, such as "dev" | "staging" | "production", and never as string. A rule that targets "prod" by mistake then fails to compile.
Because mistakes in environment targeting can lead to really bad results (e.g. releasing a dev-only feature to production), we highly recommend following a stricter set of rules for them:
envshould never be nested inside$or,$and, or$not. This makes the logic tricky to understand and follow.- Only match explicit values with strict equality.
$eqand$inare fine, but avoid$nin,$regex,$gt, and other operators.
env to its condition.
Rules for agents editing flags.ts
- Add the type first. To add a flag, add it to
AppFeatures, then toflags. TypeScript rejects a flag inflagsthat isn’t inAppFeatures, but not the reverse, so check that every flag inAppFeaturesis also defined inflags. - Make
defaultValuethe safe value. It’s what users get when no rule matches, including users with missing attributes. - Comment every flag and rule. Say what it does and why. Use only the fields in this guide.
- Don’t weaken the types. Don’t use
any,ascasts, or@ts-expect-errorto silence an error inflags.tsor in code that reads flags. Fix the flag, the attribute, or the type instead. - Don’t put secrets or personal data in
flags.ts. A file bundled into a browser or mobile app can be read by anyone. Don’t include API keys, internal URLs that should stay private, or lists of customer emails or IDs. - Don’t use flags for authorization. A flag can hide a button, but the server must still check permissions and entitlements.
- Target only attributes you pass. Add an attribute to
AppAttributesbefore using it in a condition, and pass it wherever an instance is created. A rollout excludes users with a missing or emptyhashAttributevalue. - Keep one file. Don’t create per-environment or per-feature flag files. Target environments with a top-level
envcondition, as described in Environments. - Rule order matters. The first matching rule wins. If no rules match, the
defaultValueis used. - Remove stale flags. When a flag is no longer needed (e.g. fully rolled out and stable), delete it from
AppFeaturesandflags, then remove the code branches that TypeScript reports. Stale flags are tech debt.
Testing
TypeScript checks thatflags.ts is well-formed, but not that the rules do what you intend. We recommend writing small unit tests to verify features, rules, and conditions are configured correctly. Here’s an example:
Finish the local setup
Before handing the project back:- Run the project’s typecheck and relevant tests.
- Verify safe defaults, environment overrides, and attribute targeting for the flags you added. For percentage rollouts, check that the same ID gets the same result across repeated evaluations and that a missing ID is excluded from the percentage rollout.
- Check the flag reads in the application, including attribute changes such as login or a plan change when applicable.
- Return the flags you added, their defaults and rules, the files you changed, and the verification results. Explain any checks you could not complete.

