# Feature flags

> Turn features on for some people and off for others without a deploy, with boolean and multivariate flags, payloads, targeting, local evaluation and bootstrapping.

Source: https://apphelm.dev/docs/feature-flags

A feature flag decides at runtime whether a person sees a feature. Create it once in AppHelm, check it in your code, and change who gets it (a percentage, a country, an app version, a segment) without shipping again.

Flags in AppHelm are **fail-closed**: if a flag can't be evaluated (no network, an unknown key, a key without the right scope), it reads as off. Evaluating flags never counts against your event allowance; evaluations have their own monthly cap, set by your plan, as do the number of flags and whether multivariate flags are available.

## Create a flag

Open **Flags** in the app and press **New flag**. Give it a key such as `new-checkout`; the key is what your code checks and can't be changed later. Choose a type:

| Type | Your code reads | Use it for |
| --- | --- | --- |
| Boolean | `true` when enabled, `false` otherwise | Turning one feature on or off |
| Multivariate | the variant's key (`"control"`, `"blue"` …), or `false` | Several versions of a feature, and experiments |
| Remote config | `true`, plus a JSON payload | Values you want to change without a release (limits, copy, URLs). Served to everyone: it takes no targeting, so use a boolean flag with a payload when you need to target one |

Then set the rollout: everyone, a percentage, or conditions on person properties, country, app version and more. The same person always gets the same answer, because assignment is a stable hash of the flag and the person's id.

## Check a flag

Check the flag where the feature starts. Browser and mobile SDKs evaluate every flag for the current person in one request when they start, so reading a flag afterwards never blocks. Server SDKs take the person's id on each call.

Next.js — app/checkout/page.tsx:
```tsx
"use client";
import { useFeatureFlag } from "@sansavision/apphelm/react";

export default function Checkout() {
  const newCheckout = useFeatureFlag("new-checkout");
  return newCheckout ? <NewCheckout /> : <OldCheckout />;
}
```

React:
```tsx
import { useFeatureFlag } from "@sansavision/apphelm/react";

function Checkout() {
  const newCheckout = useFeatureFlag("new-checkout"); // false until flags load, then the answer
  return newCheckout ? <NewCheckout /> : <OldCheckout />;
}
```

Vue / Nuxt — Checkout.vue (script setup):
```ts
import { useFeatureFlag } from "@sansavision/apphelm/vue";

const newCheckout = useFeatureFlag("new-checkout"); // ComputedRef<boolean>
```

Svelte / SvelteKit — Checkout.svelte:
```ts
// `apphelm` is the object createApphelm() returned in your layout.
const newCheckout = apphelm.featureFlag("new-checkout"); // a store: use $newCheckout in markup
```

JavaScript (browser):
```js
if (analytics.isEnabled("new-checkout")) renderNewCheckout();
```

React Native / Expo:
```ts
if (await mobile.isEnabled("new-checkout")) renderNewCheckout();
```

iOS (Swift):
```swift
if await apphelm.isEnabled("new-checkout") {
  showNewCheckout()
}
```

Android (Kotlin):
```kotlin
if (Apphelm.isFeatureEnabled("new-checkout")) renderNewCheckout() // never blocks
```

Flutter:
```dart
if (apphelm.isFeatureEnabled('new-checkout')) showNewCheckout(); // never blocks
```

Node.js:
```ts
if (await apphelm.isEnabled("new-checkout", user.id)) renderNewCheckout();
```

Python:
```python
if apphelm.is_enabled("new-checkout", user.id, product_id="prd_…"):
    render_new_checkout()
```

Java / Kotlin (JVM):
```kotlin
// One client serves every person: pass the distinct id to person().
if (apphelm.person(user.id).isEnabled("new-checkout")) renderNewCheckout() // blocking, fail-closed
```

Go:
```go
if client.IsEnabled(ctx, "new-checkout", user.ID, nil) {
	renderNewCheckout()
}
```

Ruby:
```ruby
render_new_checkout if APPHELM.is_enabled("new-checkout", user.id)
```

PHP:
```php
if ($apphelm->isEnabled('new-checkout', (string) $user->id)) {
    renderNewCheckout();
}
```

.NET (C#):
```csharp
if (await apphelm.IsFeatureEnabledAsync("new-checkout", user.Id))
{
    RenderNewCheckout();
}
```

Rust:
```rust
if apphelm.is_enabled("new-checkout", &user.id, &FlagOptions::new()) {
    render_new_checkout();
}
```

Elixir:
```elixir
if Apphelm.enabled?("new-checkout", user.id), do: render_new_checkout()
```

HTTP (curl):
```bash
curl -X POST https://apphelm.dev/api/v1/flags/evaluate \
  -H "Authorization: Bearer $APPHELM_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{"productId":"prd_…","distinctId":"user-123","flagKey":"new-checkout"}'
# Each row: { key, enabled, variant, payload, reason, flagType }
```

**Only for JavaScript (browser), React, Next.js, Vue / Nuxt, Svelte / SvelteKit:**

In the browser, flags load after the SDK starts. Until they arrive, and while server rendering, every flag reads `false`, so render the old behaviour first. The React hooks re-render when flags arrive (`useFlagsReady()` tells you when).

**Only for Android (Kotlin), Flutter:**

The app loads every flag for the person in one request at start-up and again after `identify` and `reset`, and keeps the last answers on the device, so a flag reads its last known value offline.

## Variants and payloads

For a multivariate flag, read the variant instead of a boolean. `getFeatureFlag` answers the variant's key for a multivariate flag, `true` for an enabled boolean flag, and `false` when the flag is off.

Node.js:
```ts
const variant = await apphelm.getFeatureFlag("pricing-test", user.id); // "blue", true or false
```

Python:
```python
variant = apphelm.get_feature_flag("org_…", "prd_…", "pricing-test", user.id)  # variant, True or False
```

Android (Kotlin):
```kotlin
val variant = Apphelm.getFeatureFlag("pricing-test") // "blue", true or false
val limits = Apphelm.getFeatureFlagPayload("upload-limits") // the JSON payload, or null
```

Java / Kotlin (JVM):
```kotlin
val person = apphelm.person(user.id, mapOf("plan" to "pro")) // person properties for this evaluation
val variant = person.getFeatureFlag("pricing-test")         // "blue", true or false
val payload = person.getFeatureFlagPayload("pricing-test")  // maps, lists, strings, numbers or null
```

Flutter:
```dart
final variant = apphelm.getFeatureFlag('pricing-test');        // 'blue', true, false or null
final limits = apphelm.getFeatureFlagPayload('upload-limits'); // JSON payload or null
```

Go:
```go
payload := client.GetFeatureFlagPayload(ctx, "pricing-test", user.ID, nil) // decoded JSON or nil
```

Ruby:
```ruby
APPHELM.get_feature_flag_payload("pricing-test", user.id) # parsed JSON or nil
```

PHP:
```php
$payload = $apphelm->getFeatureFlagPayload('pricing-test', (string) $user->id); // decoded JSON or null
```

.NET (C#):
```csharp
var value = await apphelm.GetFeatureFlagAsync("pricing-test", user.Id);
JsonElement? payload = await apphelm.GetFeatureFlagPayloadAsync("banner", user.Id);
```

Rust:
```rust
let payload = apphelm.get_feature_flag_payload("banner", &user.id, &options); // Option<serde_json::Value>
```

Elixir:
```elixir
Apphelm.get_feature_flag("pricing-test", user.id)   # "b", true or false
Apphelm.get_feature_flag_payload("banner", user.id) # the payload when the flag is on
```

## Evaluate locally on a server

By default a server SDK asks AppHelm for each answer. With **local evaluation** it downloads the flag configs instead, polls them every 10 seconds, and answers in memory, which is faster and keeps working through short network failures.

Node.js:
```ts
// Needs a server key with products:read.
const flags = await apphelm.localFlags({ productId: "prd_…" });
if (await flags.isEnabled("new-checkout", user.id)) renderNewCheckout();
flags.stop(); // on shutdown
```

Geo, device, app version, person-property and other-flag conditions are decided in memory from what you pass (`context` and `traits`). Flags that need data only AppHelm holds (a segment, an early-access condition, assignment kept across sign-in) can't be. Depending on the SDK they are answered by the API (Go) or read as off with the reason `server_evaluation_required` (Node); your SDK's README says which.

> **Local evaluation needs products:read:** Flag configs carry the assignment salt, so loading them needs a server key with the `products:read` scope. With an `events:write`-only key nothing loads and every flag is off. Keys shipped in mobile apps should be `events:write` only, so apps use remote evaluation.

## Target the right people

A flag's rollout combines conditions, each matching on something the SDK sends or AppHelm knows:

- **Person properties** you set with `identify`, such as `plan` or `company_size`.
- **Place**: country, region, city or continent, from the request's location or from `context` you pass.
- **Device and app**: browser, operating system, device type and app version (for example `app_version >= 3.0`).
- **Segments and percentages**: a saved segment, a share of everyone who matches, and a different rollout per environment.
- **Other flags**: only when another flag is on.
- **Early access**: people who opted in to a feature.

On a server, the request comes from your server, not the person's device, so pass the device details yourself (`context`: country, app version and so on) and any `personProperties` you know. You can also change targeting through the API, with a server key that has the `flags:write` scope:

```bash
curl -X PATCH https://apphelm.dev/api/v1/flags/$FLAG_ID \
  -H "Authorization: Bearer $APPHELM_API_KEY" -H "Idempotency-Key: $(uuidgen)" -H "Content-Type: application/json" \
  --data '{"conditions":[{"type":"geo","field":"country","operator":"in","values":["SE","NO"]},{"type":"app_version","operator":"gte","value":"3.0"}],"expectedVersion":4}'
```

## Flags and experiments

An [experiment](https://apphelm.dev/docs/experiments) counts a person from their first exposure event (`apphelm.flag_evaluated`). Reading a flag sends it:

- **Browser**: the first time the page reads each flag (`isEnabled`, `getFeatureFlag`, the React, Vue and Svelte helpers), for every flag, once per flag per page load. It needs analytics consent.
- **Server and mobile SDKs**: when `getFeatureFlag` or `isEnabled` reads a flag a running experiment uses, once per flag, person and variant. Pass `sendExposure` to force it on or off, or call `recordExposure` after local evaluation, which never sends one. Python's `is_enabled` sends none; use `get_feature_flag` for experiment flags.

The results divide by those exposures, so read the flag where the person actually sees the difference, not earlier. While an experiment runs, its flag's variants can't change and the flag can't be archived.

## Best practices

- **Check once, near the feature.** Read the flag where the behaviour forks and pass the answer down, so one screen never shows a mix of old and new.
- **Write the off path first.** Flags are off until they load and when anything fails, so the old behaviour must always work.
- **Name flags for the feature** (`new-checkout`), not for the experiment or the date, and archive them when the rollout is done.
- **Keep server keys on servers.** Mobile and browser code use keys that can't read flag configs; that is intended.

## Troubleshooting

| Symptom | Likely cause | What to do |
| --- | --- | --- |
| A flag is always `false` in the browser | The key's allowed origins don't include this page, the flag is a draft or disabled, or the code read it before flags loaded | Add the origin to the key in Settings, activate the flag, and wait for `flagsReady` (or `useFlagsReady()`) before deciding |
| A flag reads `false` with reason `server_evaluation_required` in the browser | The flag is marked server-only | Evaluate it on your server with a server key and pass the answer to the page, for example in the SDK's `bootstrap` option |
| Every flag is off and the API answers 429 `flag_evaluation_limit` | The monthly flag evaluation cap is reached | Evaluate locally on servers (it isn't metered), or raise the plan |
| Local evaluation returns `false` for every flag | The server key lacks `products:read` | Create a server key with `products:read`, or use remote evaluation |
| A person sees a different variant on another device | They were anonymous on one device | Call `identify` with the same user id on every device |
| Changing a flag's variants or archiving it fails | A running experiment uses the flag (a draft experiment also blocks archiving) | Stop or ship the experiment first |
