# Keys, scopes and environments

> Which key each platform uses, what every scope allows, how browser keys are tied to origins, how to rotate and revoke keys, and how production and staging are kept apart.

Source: https://apphelm.dev/docs/keys-and-environments

AppHelm has two kinds of key. A **browser key** (`ahl_pub_…`) is public and only works from the origins you list for it. A **server key** (`ahl_live_…`) is secret and can do exactly what its scopes allow. Mobile apps use a server key too, but one that can only send events.

## Workspaces and products

- A **workspace** (`org_…`) is your organisation: members, billing, keys and settings. Every key belongs to one workspace.
- A **product** (`prd_…`) is one app, site or service you measure. Events, flags, issues, replays and dashboards belong to a product. How many products you can have depends on your plan; archived products and the demo product do not count.

Neither id is secret. Both appear in Setup and on the product's page, and every SDK takes them as options. A request whose `workspaceId` or `productId` is not the key's is refused with `403 scope_mismatch`.

The **demo product** has no keys and accepts no data from any key (`409 demo_product_read_only`). Use it to look around, not to test your installation.

## Which key to use

| Where the code runs | Key | Scopes | Safe to ship? |
| --- | --- | --- | --- |
| Browser: Next.js, React, Vue, Svelte, Angular, plain HTML | Browser key, `ahl_pub_…` | None; fixed to one product and its origins | Yes, by design |
| Mobile app: React Native, iOS, Android, Flutter | Server key, `ahl_live_…` | `events:write` only, for that product only; add `feedback:write` only if the app calls `captureFeedback` | Treat it as public: anyone can extract it from the app |
| Server: Node, Python, JVM, Go, Ruby, PHP, .NET, Rust, Elixir, HTTP | Server key, `ahl_live_…` | What the code needs (usually `events:write`) | No. Server environment only |
| CI: source maps, debug files, deploys | Server key | `events:write` | No. CI secret store only |
| CLI, scripts, MCP clients, AI agents | Server key | What the task needs | No |

> **Never put a broad server key in an app or a page:** A key with `products:read` can read flag configs, including the salt that decides who gets which variant. A key with write scopes can change your workspace. Only browser keys and keys limited to `events:write` (plus `feedback:write` for in-app feedback, which lets the key post feedback for that product) may leave your servers.

## Browser keys

A browser key belongs to **one product** and lists the **exact origins** it accepts. Every request from the browser SDK carries the key in an `X-Apphelm-Key` header, and AppHelm checks the request's `Origin` against the list before it reads anything else.

- **An origin is a scheme, host and port**: `https://app.example.com`, `http://localhost:3000`. A path is ignored. When you leave the scheme out in Setup, `https://` is assumed.
- **Matches are exact.** `https://example.com` does not cover `https://www.example.com`, and `http://localhost:3000` does not cover `http://localhost:5173`. Wildcards are not supported.
- **One key per site or environment.** Setup creates a browser key for one origin. To collect from another origin (a second domain, a staging site, local development), create another browser key for that origin in Setup (**Create browser key**). Keys created through the API or the MCP server (with `products:write`) can list 1 to 5 `https://` origins.
- **A wrong origin or key** is answered `401 invalid_project_key`. The browser SDK keeps the batch and tries again; `debug: true` prints `POST /api/events was refused: 401`.

What a browser key can do: send events, page views, errors, transactions, replays, profiles, logs and error reports for its own product, load flags (`/api/flags/bootstrap`) and ask for and answer surveys. What it cannot do: read any data, send to another product, or send customer signals (`apphelm.identify`, `apphelm.group`, `apphelm.goal`, `apphelm.outcome`), which need a server key (`403 server_authority_required`). The browser SDK's own `identify` call is not a customer signal and works with a browser key.

Mobile SDKs use a browser key too, but only for surveys and replay uploads, passed as `surveyKey` with one of its origins as `surveyOrigin`.

## Server keys

A server key is created by an owner or administrator and shown **once**. AppHelm stores only its SHA-256 digest, so a lost key cannot be shown again: create another one.

- **Scopes** decide what the key can do (below).
- **Products**: a key can be limited to up to 50 products, or cover every product. Only someone with access to all products can create an all-products key. A request for a product outside the key's list is refused with `403 product_scope_denied`.
- **Limit**: a workspace holds at most 10 active server keys. Creating an eleventh is refused with `409 key_limit`; revoke one you no longer use first.
- **Expiry**: server keys do not expire. Revoke them when they are no longer needed.
- **Last used**: the key list shows when each key was last used, so you can find keys nothing uses.

Where keys are created:

| Where | What it creates |
| --- | --- |
| Setup (`/app/onboarding`) | A server key for one product with `events:write` only. This is the key for servers, mobile apps and CI. |
| Settings → API keys → Key for an AI agent | An all-products key with `products:read`, and optionally `products:write`, `experiments:read` and `experiments:write`. |
| `apphelm login` | A key approved in the browser, with the scopes and products the approver chooses. It is stored on that computer only (see [CLI reference](https://apphelm.dev/docs/cli)). |

Send a server key as `Authorization: Bearer ahl_live_…`. A missing or unknown key is answered `401 unauthorized`; a key without the needed scope `403 scope_denied`.

## Scopes

Most scopes are given to a key by default when no list is chosen (for example on the `apphelm login` approval page). Scopes marked **explicit** are never given by default: an owner or administrator must tick them by name, because they change what your users see, send data to third parties or reach personal data.

### Sending data

| Scope | Allows |
| --- | --- |
| `events:write` | Send events, exceptions, transactions and spans (`/api/v1/traces`), logs, profiles, native crashes, deploys, cron check-ins, source maps and debug files. Evaluate flags and read remote config for the key's products. |
| `logs:write` | Send logs (`/api/v1/logs`). `events:write` also allows it. |
| `customers:write` | Send customer signals: identify with traits and their sources, outcomes. |
| `feedback:write` | Send feedback with its source receipt. |
| `usage:write` | Record measured usage. |
| `status:write` | Report a product's status to its status page (`apphelm heartbeat`). |
| `privacy:write` | File privacy requests: deletion and suppression. |

### Reading data

| Scope | Allows |
| --- | --- |
| `products:read` | List products and their health, and read flag configs for local evaluation. |
| `metrics:read` | Read approved metrics and run queries over them. |
| `analytics:read` | Read saved insights, dashboards, annotations, alerts, cohorts and recent events. |
| `insights:read` | Read evidence-backed insights and their evidence. |
| `sessions:read` | Search consent-filtered session metadata. Captured text is never returned. |
| `issues:read` | Read error issues and their events, releases, and traces and spans. |
| `logs:read` | Search a product's logs. |
| `experiments:read` | Read experiments and their results. |
| `surveys:read` | Read surveys and their results. |
| `feedback:read` | Read feedback. |
| `customers:read` | Read customer profiles, with personal data masked. |
| `accounts:read` | Read account summaries. |
| `segments:read` | Read segments and cohorts. |
| `outcomes:read` | Read outcome definitions and results. |
| `findings:read` | Read qualified findings and their evidence. |
| `interventions:read` | Read interventions and their results. |
| `roadmap:read` | Read the roadmap and its evidence packs. |
| `incidents:read` | Read incidents and status history. |
| `usage:read` | Read usage and cost summaries. |
| `alerts:read` | Read issue and metric alert rules and when they last fired. |
| `monitors:read` | Read cron monitors and their check-ins, and uptime checks and their results. |
| `pipelines:read` | List data pipelines and their deliveries and runs. Credentials are never returned. |
| `imports:read` | Read PostHog migrations and data sources. |
| `integrations:read` | Read integration status. |
| `privacy:read` | Reveal personal data where an endpoint allows it. Every use is audited. |

### Changing things

| Scope | Explicit | Allows |
| --- | --- | --- |
| `insights:write` | | Change insight state and leave feedback on insights. |
| `issues:write` | | Triage issues: resolve, ignore, assign, set priority. |
| `segments:write` | | Change segments. |
| `outcomes:write` | | Draft and change outcome definitions. |
| `interventions:write` | | Draft interventions. |
| `roadmap:write` | | Change roadmap items. |
| `actions:draft` | | Draft actions and flag changes for a person to review; nothing is applied. |
| `ai:investigate` | | Ask Beam questions. Uses the workspace's AI credits. |
| `products:write` | Yes | Create products and their browser keys. Needs an all-products key. It cannot create server keys. |
| `flags:write` | Yes | Create, change, schedule and archive feature flags, including turning them on or off for live traffic. |
| `experiments:write` | Yes | Create, launch, stop and ship experiments, and set a product's holdout. |
| `surveys:write` | Yes | Create, launch, stop and archive surveys. |
| `analytics:write` | Yes | Create and change saved insights, dashboards, annotations, insight alerts, subscriptions, saved log searches and log alerts. |
| `cohorts:write` | Yes | Create static cohorts and change their members. Flags can target cohorts. |
| `alerts:write` | Yes | Create, change, pause and delete alert rules, which notify members and send webhooks. |
| `monitors:write` | Yes | Create, change and delete cron monitors and uptime checks. |
| `pipelines:write` | Yes | Create, change, test, pause and delete data pipelines, which send data to third parties. |
| `imports:write` | Yes | Start, pause, resume, cancel and undo PostHog migrations, and manage data sources. |
| `members:read` | Yes | List members, roles, invitations and seats. Needs an all-products key. |
| `members:write` | Yes | Invite, change and remove members. Needs an all-products key. |
| `audit:read` | Yes | Read the workspace audit log. |

Writes made with a key are recorded in the audit log under the key and the person who created it. Several explicit scopes (`analytics:write`, `alerts:write`, `monitors:write`, `pipelines:write`, `imports:write`, `members:write`, `audit:read`) also need that person to be an owner or administrator.

The `registry:*` and `ecosystem:execute` scopes exist for Sansa Vision's internal services; a customer key has no use for them.

## Rotate and revoke keys

Revoking takes effect straight away: requests with the key are refused, data already stored is kept and other keys keep working. To replace a key without losing events:

### Create the new key
Server key: in Setup, or with the same scopes on the CLI approval page. Browser key: in Setup, for the same origin. If the workspace already has 10 active server keys, revoke an unused one first.

### Deploy it
Put it in your secret store or environment and deploy every service, app build and CI pipeline that used the old key. Mobile apps keep the old key until users update, so leave it active until old versions are rare.

### Check the old key is idle
Its **last used** time in the key list stops moving once nothing sends with it.

### Revoke the old key
In Setup, under **Manage server API keys** or **Manage browser keys**.

If a server key leaks, revoke it first and replace it second. A leaked browser key can only send data from its own origins, but revoke and replace it if it is being abused.

To stop all collection at once (for example during an incident), an owner can pause collection for the workspace. Browser keys are then answered `202 { accepted: false, reason: "collection_paused" }` and server ingest `409 collection_paused`; nothing is stored or billed.

## Environments

An **environment** is a label such as `production`, `staging` or `development` that the SDK sends with errors, transactions, sessions and logs. It is a free text option (at most 40 characters), not a setting in AppHelm, and keys are not tied to an environment.

Use it to:

- **Filter issues and releases.** Issue search takes `environment:production`, and release health and deploys are recorded per environment.
- **Roll flags out per environment.** A flag can have its own rollout per environment. When a flag has environment rollouts, a request that names no environment, or one the flag does not list as active, reads the flag as **off** (reason `environment_excluded`). So if you use environment rollouts, pass the environment to flag evaluation everywhere.

How each SDK sends the environment:

Next.js:
```ts
<ApphelmProvider options={{ key, workspaceId, productId, environment: "staging" }}> // errors and flags
```

React:
```ts
<ApphelmProvider options={{ key, workspaceId, productId, environment: "staging" }}> // errors and flags
```

Vue / Nuxt:
```ts
createBrowserSdk({ key, workspaceId, productId, environment: "staging" }); // errors and flags
```

Svelte / SvelteKit:
```ts
createBrowserSdk({ key, workspaceId, productId, environment: "staging" }); // errors and flags
```

JavaScript (browser):
```js
createBrowserSdk({ key, workspaceId, productId, environment: "staging" }); // errors and flags
```

React Native / Expo:
```ts
createReactNativeSdk({ apiKey, workspaceId, productId, environment: "staging" }); // errors, sessions
await apphelm.isEnabled("new-checkout", { environment: "staging" });             // flags, per call
```

iOS (Swift):
```swift
let options = ApphelmOptions(apiKey: key, workspaceId: "org_…", productId: "prd_…", environment: "staging")
let on = await apphelm.isEnabled("new-checkout", environment: "staging") // flags, per call
```

Android (Kotlin):
```kotlin
Apphelm.setup(this, ApphelmConfig(BuildConfig.APPHELM_API_KEY, "org_…", "prd_…").apply {
    environment = "staging"      // errors, crashes, sessions
    flagsEnvironment = "staging" // flags
})
```

Flutter:
```dart
ApphelmConfig(apiKey: key, workspaceId: 'org_…', productId: 'prd_…', environment: 'staging', flagsEnvironment: 'staging')
```

Node.js:
```ts
const apphelm = new Apphelm({ apiKey, workspaceId, productId, environment: "staging" });  // errors, transactions
await apphelm.isEnabled("new-checkout", user.id, { environment: "staging" });             // flags, per call
```

Python:
```python
apphelm.init(api_key=key, workspace_id="org_…", product_id="prd_…", environment="staging")
apphelm_client.is_enabled("new-checkout", user.id, product_id="prd_…", environment="staging")  # flags
```

Go:
```go
client, _ := apphelm.New(apphelm.Config{APIKey: key, WorkspaceID: "org_…", ProductID: "prd_…", Environment: "staging"})
client.IsEnabled(ctx, "new-checkout", user.ID, &apphelm.FlagOptions{Environment: "staging"}) // flags
```

Ruby:
```ruby
APPHELM = Apphelm::Client.new(api_key: key, workspace_id: "org_…", product_id: "prd_…", environment: Rails.env)
```

PHP:
```php
$apphelm = new Client(apiKey: $key, workspaceId: 'org_…', productId: 'prd_…', environment: 'staging');
// Laravel: APPHELM_ENVIRONMENT, which defaults to APP_ENV
```

.NET (C#):
```csharp
new ApphelmOptions { ApiKey = key, WorkspaceId = "org_…", ProductId = "prd_…", Environment = builder.Environment.EnvironmentName }
```

Rust:
```rust
Options::new(key).workspace_id("org_…").product_id("prd_…").environment("staging")
```

Elixir:
```elixir
config :apphelm, api_key: key, workspace_id: "org_…", product_id: "prd_…", environment: "staging"
```

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","environment":"staging"}'
```

### Staging: same product or a separate one

| Approach | Good for | Watch out for |
| --- | --- | --- |
| **One product, an `environment` label** | Comparing releases across environments; one set of flags with per-environment rollouts | Staging events count towards the product's analytics and your event allowance. Filter by environment where it matters. |
| **A separate staging product** | Keeping test traffic out of funnels, retention and experiments entirely | Flags, dashboards and alerts are per product, so you set them up twice. Each product needs its own keys. |

Either way, give staging its own browser key for its own origin, and turn sending off in automated tests with `enabled: false`.

## Rate limits and caps

| Limit | Applies to | When reached |
| --- | --- | --- |
| 240 requests a minute per client address, and 2,400 a minute per browser key, per Cloudflare location | Every browser-key request | `429 rate_limited` with `Retry-After: 60` |
| 2,400 requests a minute per server key, per location | Logs (`/api/v1/logs`) and traces (`/api/v1/traces`) | `429 rate_limited` with `Retry-After: 10`. Send more lines or spans per request. |
| Monthly event allowance | All event ingest | `429 event_limit` (unless your cap behaviour adds a pre-approved block) |
| Monthly flag evaluations | Flag evaluation and remote config | `429 flag_evaluation_limit`; browser flags fail closed. Evaluate locally on servers to avoid it. |
| 20 deploys an hour per product | `/api/v1/deploys` | `429 deploy_rate_limited` |
| 60 searches a minute per key | Issue event and span search | `429 rate_limit_exceeded` with `Retry-After` |
| 60 SQL queries a minute per workspace, one at a time | `/api/v1/query/sql`, the SQL editor and MCP | `429 sql_rate_limited`, `429 sql_busy` |
| 64,000 bytes per event request, 50 events per batch | Event ingest | `400 invalid_request`, `422 batch_too_large` |

Browser-key traffic is also filtered: crawlers, headless browsers, plain HTTP clients and requests without a user agent are answered `202 { accepted: false, reason: "bot_filtered" }`, and requests from networks the workspace marked as its own team's `202 … "internal_traffic"`. Nothing is stored or billed for them. Server-key traffic is not bot-filtered.

## Troubleshooting

| Symptom | Likely cause | What to do |
| --- | --- | --- |
| `401 invalid_project_key` from the browser | The page's origin is not on the key, or the key was revoked | Compare the page's exact origin (scheme, host and port) with the key's in Setup; create a browser key for the new origin |
| `401 unauthorized` from a server | Missing, mistyped or revoked server key | Check the `Authorization: Bearer` header and the environment variable; create a new key if it was revoked |
| `403 scope_denied` | The key lacks the scope the endpoint needs | The error message names the scope; create a key that has it |
| `403 product_scope_denied` or `scope_mismatch` | The key is limited to other products, or the body names another workspace or product | Use the right `productId`, or a key for that product |
| `409 key_limit` | The workspace has 10 active server keys | Revoke unused keys (check their last used time) |
| A flag is off in one environment only | The flag has environment rollouts and the request names no environment, or another one | Pass the environment to flag evaluation (see [Environments](#environments)) |
