# Events and autocapture

> Send custom events with properties from every platform, see what autocapture records and never records, and learn how events are queued, filtered, limited and sent over HTTP.

Source: https://apphelm.dev/docs/events

An **event** is one thing that happened: `signup_completed`, `report_exported`, a page view, a screen view. Every chart, funnel, experiment and alert in AppHelm counts events. You send the events that matter to your business yourself, and the browser and mobile SDKs record page views, screens, clicks and app lifecycle for you.

Each event has a **name**, a **distinct id** (who did it), optional **properties** (`plan: "pro"`, `items: 3`) and a time. AppHelm stores who did it as two hashes of the distinct id, never the id itself. [Users, people and groups](https://apphelm.dev/docs/identify) explains ids, sign-in and accounts.

## Send an event

Call the SDK where the thing happens. Browser and mobile SDKs know who the person is, so you pass only the name and properties. Server SDKs serve many people, so each call names the person with `distinctId`: your user id, or the id the browser SDK was given.

Next.js — app/checkout/pay-button.tsx:
```tsx
"use client";
import { useTrack } from "@sansavision/apphelm/next";

export function PayButton() {
  const track = useTrack();
  return <button onClick={() => track({ name: "checkout_started", properties: { items: 3 } })}>Pay</button>;
}
```

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

function PayButton() {
  const track = useTrack(); // events sent before the client exists are held (up to 100)
  return <button onClick={() => track({ name: "checkout_started", properties: { items: 3 } })}>Pay</button>;
}
```

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

const track = useTrack(); // does nothing while server rendering
const pay = () => track({ name: "checkout_started", properties: { items: 3 } });
```

Svelte / SvelteKit — PayButton.svelte:
```ts
// `apphelm` is the object createApphelm() returned in your layout.
const pay = () => apphelm.track({ name: "checkout_started", properties: { items: 3 } });
```

JavaScript (browser):
```js
analytics.track({ name: "checkout_started", properties: { items: 3 } });
```

React Native / Expo:
```ts
mobile.track({ name: "checkout_started", properties: { items: 3 } });
```

iOS (Swift):
```swift
apphelm.track("checkout_started", properties: ["items": 3])
```

Android (Kotlin):
```kotlin
Apphelm.track("checkout_started", mapOf("items" to 3))
```

Flutter:
```dart
Apphelm.instance.track('checkout_started', properties: {'items': 3});
```

Node.js:
```ts
await apphelm.capture({ distinctId: user.id, event: "checkout_started", properties: { items: 3 } });
```

Python:
```python
apphelm.capture("org_…", "prd_…", distinct_id=user.id, event_name="checkout_started", properties={"items": 3})
```

Java / Kotlin (JVM):
```kotlin
apphelm.track("checkout_started", mapOf("items" to 3))
```

Go:
```go
client.Capture(apphelm.Capture{
	DistinctID: user.ID,
	Event:      "checkout_started",
	Properties: apphelm.Properties{"items": 3},
})
```

Ruby:
```ruby
APPHELM.capture(distinct_id: user.id, event: "checkout_started", properties: { items: 3 })
```

PHP:
```php
$apphelm->capture(distinctId: (string) $user->id, event: 'checkout_started', properties: ['items' => 3]);
```

.NET (C#):
```csharp
apphelm.Capture(user.Id, "checkout_started", new Dictionary<string, object?> { ["items"] = 3 });
```

Rust:
```rust
apphelm.capture(Event::new(&user.id, "checkout_started").property("items", 3))?;
```

Elixir:
```elixir
Apphelm.capture(user.id, "checkout_started", %{items: 3})
```

HTTP (curl):
```bash
curl -X POST https://apphelm.dev/api/v1/events \
  -H "Authorization: Bearer $APPHELM_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{"workspaceId":"org_…","productId":"prd_…","eventName":"checkout_started","properties":{"distinct_id":"user-123","items":3}}'
# 202 {"accepted":true,"eventId":"…","storedEvents":1}
```

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

**The browser sends nothing until analytics consent.** Events tracked before `setConsent({ analytics: true })` are dropped, not queued, and so are all events in a browser with Global Privacy Control on or with `enabled: false`. Call `setConsent` from your consent banner as soon as the person agrees. [Web analytics and attribution](https://apphelm.dev/docs/web-analytics#consent-cookies-and-storage) covers consent and storage in detail.

**Only for Node.js, Python, Go, Ruby, PHP, .NET (C#), Rust, Elixir:**

**A server event needs a distinct id to count as a person.** Every server SDK's capture call requires one and raises an error without it. Pass the same id the browser uses for that person (your user id once they have signed in), and the event joins their browser events in funnels, retention, unique-people trends and experiments. Server SDKs that have a separate `ingest` call send events with no person; those count only as volume.

**Only for Node.js:**

The Node client sends each `capture` as one request and returns its promise. It rejects with an `ApphelmError` (with `status` and `code`) when AppHelm refuses the event or cannot be reached, so don't let analytics failures break a request: `void apphelm.capture(...).catch(log)` or wrap it in `try`. Pass `workspaceId` and `productId` to `new Apphelm({...})` once, or on each call.

## Properties

Properties describe the event: what was bought, which plan, how long it took. Send them as a flat object of strings, numbers and booleans.

What AppHelm keeps for charts, filters and breakdowns:

| Rule | Detail |
| --- | --- |
| Values | Strings, numbers and booleans. Nested objects, arrays and `null` are left out |
| Keys | Letters, digits, `_`, `.`, `$` and `-`, starting with a letter, `_` or `$`, at most 64 characters. Other keys are left out |
| How many | The first 20 properties, and at most 2,000 characters of JSON together. On browser events the device, browser, OS and country come first |
| Strings | Trimmed, cut to 200 characters, and scrubbed: emails, AppHelm keys, bearer tokens, secret query parameters and long hex strings are replaced |
| Sensitive names | A key that looks like a secret or contact detail is dropped: it contains `pass`, `secret`, `token`, `auth`, `cookie`, `session_id`, `email`, `phone`, `ssn`, `card`, `cvc`, `cvv` or `iban`, or is `value`, `inner_text` and similar |

> **Property names that are dropped without an error:** The sensitive-name check matches anywhere in the key, so `author_id`, `phone_model` and `gift_card_count` are dropped too. Rename them (`writer_id`, `device_model`, `gift_voucher_count`). Nothing tells you at send time; the property is simply missing from charts. `apphelm events tail` shows exactly what was kept.

AppHelm adds some properties itself. Browser events get `$device_type` (`mobile`, `tablet` or `desktop`), `$browser`, `$os` and `$country`, worked out from the request and replacing anything the browser sent under those names; the user agent and IP address themselves are not stored. Mobile SDKs add the app's details, such as `$app_version` and `$app_build` (Android and Flutter also add `$os` and `$lib`, and Android the device model). Server events get no device context, because the request comes from your server.

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

The browser SDK also drops the property keys `value`, `innerText`, `textContent`, `password`, `email` and `innerHTML` before anything is sent.

### Super properties

A super property is sent with every later event: the person's plan, the app's theme, an experiment cohort. Set it once with `register` and remove it with `unregister`. An event's own property with the same name wins.

JavaScript (browser):
```js
analytics.register({ plan: "builder" });
analytics.unregister("plan");
```

React Native / Expo:
```ts
mobile.register({ plan: "builder" }); // kept across restarts when you pass `storage`
```

iOS (Swift):
```swift
apphelm.register(["plan": "builder"]) // kept across launches
apphelm.unregister("plan")
```

Android (Kotlin):
```kotlin
Apphelm.register("plan", "builder") // kept across launches
Apphelm.unregister("plan")
```

Flutter:
```dart
apphelm.register({'plan': 'builder'}); // kept across launches
apphelm.unregister('plan');
```

Java / Kotlin (JVM):
```kotlin
apphelm.register(mapOf("plan" to "builder"))
apphelm.unregister("plan")
```

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

In the browser, registered properties and groups live in memory for the current page load only. Call `register` (and `group`) again on each load, for example right after you know who is signed in. `reset()` clears them.

Server SDKs have no super properties, because one client serves many people. Add the properties to each call instead, or wrap the call in a function of your own.

## Autocapture

The browser SDK records these events by itself once analytics consent is given. Turn it off with `autocapture: false` when you create the client, or per product in **Settings → Capture**.

| Event | When | What it carries |
| --- | --- | --- |
| `page_viewed` | On load, and on each `pushState`, `replaceState` or back/forward that changes the path | Path, referrer (origin and path only), UTM source, medium and campaign, session |
| `$pageleave` | When the page is hidden or closed | Path, time on page (at most an hour), deepest scroll in percent |
| `$autocapture` | A click, a form submit, or a change to an input, select or textarea | The element's tag, a structural selector (tags and positions only), the click's position in a 40 × 24 grid, the input's type |
| `$rageclick` | Three clicks on the same element within one second | As a click, once per burst |
| `$dead_click` | A click on something that is not a link, button or form control, after which nothing on the page changes for 700 ms | As a click |
| `$web_vitals` | When the page is hidden | LCP, INP and CLS, when the browser measured them |

**Autocapture never records** what people type or read: no input values, no element text, no ids or class names, and nothing at all from password, email, phone, one-time-code and card fields, `contenteditable` elements, or anything inside an element marked `data-apphelm="mask"`. The selector is a path of tags such as `div:nth-of-type(2)>button:nth-of-type(1)`, so it can't contain content.

**Paths that are never autocaptured**: `/auth`, `/sign-in`, `/sign-up`, `/login`, `/logout`, `/billing`, `/checkout`, `/payment`, `/admin` and `/account/security`, and everything under them. Add up to 20 more paths per product in **Settings → Capture** (each starting with `/`). Events you send yourself with `track` are not affected by these lists.

**Sampling.** **Settings → Capture** can keep a share (1–100%) of autocapture events per product. Page views and page leaves are never sampled, so sessions and bounce rate stay correct. Your own `track` calls, errors and flag exposures are never sampled.

> **Autocapture counts toward your allowance:** Each stored autocapture event is one event on your monthly allowance, like a `track` call. If clicks are noise for you, set a sample rate (page views are never sampled), or create the client with `autocapture: false` and send page views yourself with `page()`.

### Mobile autocapture

The mobile SDKs record app lifecycle and screens by themselves:

| Event | When |
| --- | --- |
| `$app_installed` | First launch with the SDK (`version`, `build`) |
| `$app_updated` | The version or build changed since the last launch (with `previous_version`, `previous_build`) |
| `$app_opened` | Launch (`from_background: false`) and each return from the background (`true`) |
| `$app_backgrounded` | The app goes to the background |
| `$screen` | A screen appears, with `$screen_name` |

**Only for iOS (Swift):**

UIKit view controllers send `$screen` automatically (`captureScreenViews`, on); the name is the type name without `ViewController`. In SwiftUI add `.apphelmScreen("Checkout")` to the view. Lifecycle events follow `captureApplicationLifecycleEvents` (on).

**Only for Android (Kotlin):**

Each Activity sends `$screen` when it starts (`captureScreenViews`, on), named by its `android:label` or its class name without `Activity`. Jetpack Navigation destinations need `ApphelmNavigationListener`, or `withApphelmObservableEffect()` with Compose. Lifecycle events follow `captureApplicationLifecycleEvents` (on).

**Only for Flutter:**

Add `ApphelmObserver()` to `navigatorObservers` (or go_router's `observers`) and each named page route sends `$screen`. Routes without a name, dialogs and sheets send nothing. Lifecycle events follow `captureApplicationLifecycleEvents` (true).

**Only for React Native / Expo:**

Lifecycle events need `appState: AppState` (and `storage` for install and update). For screens, pass `mobile.navigationTracker()` to React Navigation's `onReady` and `onStateChange`; route params are never sent unless `routeProperties` returns them.

## Page views and screens

A page view is `page_viewed` (AppHelm's name; `$pageview` from PostHog imports and the HTTP API is read the same way). A screen view is `$screen` with `$screen_name`. Both count as views in paths, entry and exit pages and sessions, and a screen's name is stored as its path.

JavaScript (browser):
```js
analytics.page({ section: "pricing" }); // a manual page view, with extra properties
```

React Native / Expo:
```ts
mobile.screen("Checkout", { step: 2 });
```

iOS (Swift):
```swift
apphelm.screen("Checkout", properties: ["step": 2])
```

Android (Kotlin):
```kotlin
Apphelm.screen("Checkout", mapOf("step" to 2))
```

Flutter:
```dart
apphelm.screen('Checkout');
```

Java / Kotlin (JVM):
```kotlin
apphelm.screen("Checkout")
```

Single-page apps are covered by autocapture, which follows the History API. Router helpers for Vue, Angular, SvelteKit and Next.js, server-side page views and everything about sessions and referrers are in [Web analytics and attribution](https://apphelm.dev/docs/web-analytics#pageviews).

## Attach events to a group

Put an event in a group (a company, a team, a project) and you can filter and break down any insight by it. Once your server has set the group's properties, its activity also shows on the **Accounts** page. The browser and mobile SDKs remember the group and add it to every later event; server SDKs take it on each call. An event carries at most 5 group types, stored as the property `$group.<type>`.

JavaScript (browser):
```js
analytics.group("company", company.id); // later events carry $groups: { company: "…" }
```

React Native / Expo:
```ts
mobile.group("company", company.id);
```

iOS (Swift):
```swift
apphelm.group(type: "company", key: company.id)
```

Android (Kotlin):
```kotlin
Apphelm.group("company", company.id)
```

Flutter:
```dart
apphelm.group('company', company.id);
```

Node.js:
```ts
await apphelm.capture({ distinctId: user.id, event: "report_exported", properties: { $groups: { company: company.id } } });
```

Python:
```python
apphelm.capture("org_…", "prd_…", distinct_id=user.id, event_name="report_exported", groups={"company": company.id})
```

Go:
```go
client.Capture(apphelm.Capture{DistinctID: user.ID, Event: "report_exported", Groups: map[string]string{"company": company.ID}})
```

Ruby:
```ruby
APPHELM.capture(distinct_id: user.id, event: "report_exported", groups: { company: company.id })
```

PHP:
```php
$apphelm->capture(distinctId: (string) $user->id, event: 'report_exported', groups: ['company' => (string) $company->id]);
```

.NET (C#):
```csharp
apphelm.Capture(user.Id, "report_exported", groups: new Dictionary<string, string> { ["company"] = company.Id });
```

Rust:
```rust
apphelm.capture(Event::new(&user.id, "report_exported").group("company", &company.id))?;
```

Elixir:
```elixir
Apphelm.capture(user.id, "report_exported", %{}, groups: %{company: company.id})
```

Group types are 1–40 letters, digits, `_` or `-`; keys are cut to 200 characters. Setting a group's name and plan is `groupIdentify`, covered in [Users, people and groups](https://apphelm.dev/docs/identify#groups-and-accounts).

## Timestamps

Every SDK stamps an event with the time it was tracked, and queued events keep that time when they are sent later. Server SDKs let you pass your own: `occurredAt` (Node, the browser and React Native), `occurred_at` (Python), `Timestamp` (Go), `timestamp:` (Ruby, PHP, .NET, Elixir) and `.timestamp()` (Rust).

> **Charts use the time AppHelm received the event:** Insights, funnels and retention bucket events by when AppHelm received them, in UTC, not by the device's clock (device clocks are often wrong). The time you sent is kept as `client_timestamp` in [SQL](https://apphelm.dev/docs/insights#sql). Sending an old `occurredAt` does not move a live event into the past.

To load history, mark each event with the property `apphelm_import: true` and send it with a server key: it is then charted at its own `occurredAt`, when that is in the past and at most 400 days old. Your plan's retention still applies from that time, so events older than your retention are deleted on the next clean-up. For PostHog history use the built-in import instead ([Migrate from PostHog](https://apphelm.dev/docs/migrate-posthog)).

## How events are sent

No SDK makes your code wait for AppHelm, except where noted. Events go into a queue and are sent in the background, each with an event id fixed when it was tracked, so a retried send is stored and billed once.

| SDK | Queue | Sends | Offline and failures |
| --- | --- | --- | --- |
| Browser | In memory: 100 events (`maxQueueSize`, up to 500) and 48,000 bytes (`maxQueueBytes`, up to 60,000) | Every 5 s (`flushIntervalMs`), at 20 events (`maxBatchSize`, up to 50), and when the page is hidden, as one batch | With no network, or a `408`, `429` or `5xx` answer, the batch goes back on the queue; any other refusal drops it. The oldest events are dropped when the queue is full. The queue does not survive a page reload |
| React Native | In `storage` if you pass one (AsyncStorage, MMKV…), else memory: 1,000 events | Every 30 s (`flushInterval`), at 20 (`flushAt`), and when the app goes to the background | Kept and resent with the same id; refused for good (a 4xx other than 408 and 429) is dropped |
| iOS | On disk, one file per event: 1,000 events | Every 30 s (`flushIntervalSeconds`), at 20 (`flushAt`), and in the background | Kept in order and resent; an event refused for good (a 4xx other than 408 and 429) is dropped |
| Android | On disk: 1,000 events | Every 30 s, at 20, and in the background | Kept and resent; refused events are dropped |
| Flutter | `shared_preferences`: 1,000 events | 30 s after the first event, at 20, and in the background | Kept in order and resent on the next flush; refused for good (a 4xx other than 408 and 429) is dropped |
| JVM (Kotlin core) | In memory (or `storageDirectory`): 100 events | Every 30 s, at 20, on a daemon thread | Kept and resent; refused events are dropped |
| Node | None: one request per call | When you call it | The promise rejects; nothing is retried |
| Python | None by default (the call sends); `background=True` (what `apphelm.init` uses) sends from a thread | When you call it | Raises `ApphelmError`, or with `background=True` goes to `on_error` |
| Go, Ruby | 10,000 events | Every 5 s, at 20 | Network errors, 408, 429 and 5xx retried 3 times with backoff; `SyncMode` / `sync_mode: true` sends during the call |
| PHP | None by default (the call sends); `batch: true` holds events in memory | At 20 events, on `flush()` and when the script ends | Retried twice; failures go to `onError`, never thrown |
| .NET | 10,000 events | Every 10 s, at 20 | Retried 3 times; undeliverable events go to `OnError` |
| Rust | 10,000 events | 10 s after the oldest, at 20 | Retried 3 times; dropped events go to `on_error` |
| Elixir | In the client process | In the background (`flush_at`, `flush_interval`) | See `Apphelm.Config` |

Flush before a short-lived process exits, or the last events are lost:

Node.js:
```ts
await apphelm.flush(2_000); // waits for sends in flight; true when they finished in time
```

Python:
```python
apphelm.flush(timeout=2.0)
```

Go:
```go
defer client.Close() // sends what is still queued
```

Ruby:
```ruby
at_exit { APPHELM.shutdown }
```

PHP:
```php
$apphelm->flush(2.0); // with batch: true; it also runs when the script ends
```

.NET (C#):
```csharp
await apphelm.FlushAsync(); // `await using` flushes on dispose
```

Rust:
```rust
apphelm.shutdown(); // also runs when the last clone of the client is dropped
```

JavaScript (browser):
```js
await analytics.flush(); // the SDK also flushes when the page is hidden
```

React Native / Expo:
```ts
await mobile.flush();
```

iOS (Swift):
```swift
await apphelm.flush()
```

Android (Kotlin):
```kotlin
Apphelm.flush() // in the background; Apphelm.flush(2_000) blocks up to 2 s off the main thread
```

Flutter:
```dart
await apphelm.flush();
```

Java / Kotlin (JVM):
```kotlin
apphelm.close() // on shutdown: stops the timer and sends what is queued
```

## Change or drop events before they are sent

`beforeSend` sees each event before it leaves the process. Return the event, changed or not, to send it, or `null` to drop it. A hook that throws drops the event, so a broken scrubbing hook never lets data through. AppHelm scrubs again on arrival either way.

JavaScript (browser):
```js
const analytics = createBrowserSdk({
  key: "ahl_pub_…", workspaceId: "org_…", productId: "prd_…",
  beforeSend: (event) => (event.name === "internal_debug" ? null : event), // { name, properties, occurredAt }
});
```

Node.js:
```ts
const apphelm = new Apphelm({
  apiKey: process.env.APPHELM_API_KEY!,
  beforeSend: (event) => (event.eventName === "internal_debug" ? null : event), // { eventName, properties, eventId, … }
});
```

React Native / Expo:
```ts
const mobile = createReactNativeSdk({
  apiKey, workspaceId: "org_…", productId: "prd_…",
  beforeSend: (event) => (event.eventName === "internal_debug" ? null : event),
});
```

iOS (Swift):
```swift
options.beforeSend = { properties in
  properties["$event_name"] as? String == "internal_debug" ? nil : properties
}
```

Java / Kotlin (JVM):
```kotlin
ApphelmOptions(/* … */, beforeSend = { event ->
    if (event["\$event_name"] == "internal_debug") null else event - "email"
})
```

Flutter:
```dart
ApphelmConfig(/* … */, beforeSend: (event) => event.name == 'internal_debug' ? null : event)
```

Python:
```python
apphelm = Apphelm(api_key=os.environ["APPHELM_API_KEY"],
                  before_send=lambda event: None if event["eventName"] == "internal_debug" else event)
```

Ruby:
```ruby
before_send: ->(event) { event["properties"].delete("email"); event }
```

PHP:
```php
beforeSend: function (array $event): ?array {
    unset($event['properties']['email']);
    return $event;
},
```

| SDK | What the hook gets |
| --- | --- |
| Browser | Each queued event (`name`, `properties`, `occurredAt`), once, when it is sent. Replay is not affected |
| Node, React Native, Python | The whole event: `eventName`, `properties`, `eventId` |
| iOS, Kotlin and Android | The properties, with the event's name as `$event_name` (read-only, removed before sending) |
| Flutter | An `ApphelmEvent` with `name` and `properties` |
| Go, Ruby, PHP, .NET, Rust, Elixir | The whole event body (`BeforeSend`, `before_send:`, `beforeSend`, `before_send`) |

Every SDK passes every event through it: your events, screens, identify, alias and group events, flag exposures, exceptions and transactions.

## Name your events

Good names make insights readable for people who did not write the code.

- **Object and past-tense action, in snake_case**: `signup_completed`, `report_exported`, `invoice_paid`. One style across every platform, so web and mobile events with the same meaning share a name and add up.
- **Name the outcome, not the button**: `checkout_started`, not `blue_button_clicked`. Autocapture already records clicks.
- **Put variation in properties**, not names: `report_exported` with `format: "csv"`, not `report_exported_csv`.
- **Never put personal data in names or property values.** Names are not scrubbed like property strings, and names show in every chart.
- **Don't start your own names with `$` or `apphelm.`**, which are AppHelm's.

### Reserved events

These names have a meaning to AppHelm. Send them only as described.

| Event | Sent by | Meaning |
| --- | --- | --- |
| `page_viewed`, `$pageview` | Browser autocapture, `page()`, HTTP | A page view |
| `$pageleave`, `$autocapture`, `$rageclick`, `$dead_click`, `$web_vitals` | Browser autocapture | See [Autocapture](#autocapture) |
| `$screen` | Mobile SDKs | A screen view, with `$screen_name` |
| `$app_installed`, `$app_updated`, `$app_opened`, `$app_backgrounded` | Mobile SDKs | App lifecycle |
| `$identify`, `$create_alias`, `$groupidentify` | `identify`, `alias`, `group` | Identity and groups ([Users, people and groups](https://apphelm.dev/docs/identify)) |
| `apphelm.identify`, `apphelm.group`, `apphelm.goal`, `apphelm.outcome` | Server SDKs | Customer signals; refused from a browser key |
| `apphelm.flag_evaluated`, `apphelm.experiment_exposed` | Flag reads | [Experiment](https://apphelm.dev/docs/experiments) exposures |
| `$exception`, `$transaction`, `$session` | Error and tracing code | [Errors](https://apphelm.dev/docs/errors), [tracing](https://apphelm.dev/docs/tracing), [release health](https://apphelm.dev/docs/release-health) |
| `$ai_generation`, `$ai_embedding`, `$ai_span`, `$ai_trace`, `$ai_feedback`, `$ai_metric` | LLM helpers | [LLM analytics](https://apphelm.dev/docs/llm-analytics) |
| `$install` | `recordInstall()` on mobile | Ad-measurement installs |
| `apphelm_batch` | Browser SDK, HTTP | An envelope of up to 50 events, not an event itself |

## Keep your own team out

Register `apphelm_internal: true` once you know the signed-in person works for you. Every later event from that browser, autocapture included, is dropped before it is stored or billed, and the answer is `202 {"accepted":false,"reason":"internal_traffic"}`. Server events with `apphelm_internal: true` in their properties are dropped the same way. Owners and admins can also exclude an office network in **Settings → Capture**. [Web analytics](https://apphelm.dev/docs/web-analytics#keep-your-own-team-out) has the details.

JavaScript (browser):
```js
if (user.isStaff) analytics.register({ apphelm_internal: true });
```

## Limits and your allowance

| Limit | Value | What happens past it |
| --- | --- | --- |
| Request body | 64,000 bytes | `400 invalid_request` |
| Event name | 1–100 characters | `422 missing_fields` (a longer name counts as missing) |
| Events in one `apphelm_batch` | 50 | `422 batch_too_large` |
| Properties kept per event | 20, and 2,000 characters of JSON | The rest are not stored |
| Groups per event | 5 types | The rest are not stored |
| Browser requests | 240 a minute per visitor IP and 2,400 a minute per browser key, per Cloudflare location | `429 rate_limited` with `Retry-After: 60` |
| Monthly events | Your plan's allowance, shown in **Plans & billing** | See below |

Every stored event counts once against the workspace's monthly allowance: each event in a batch, each autocapture event, each error. Flag evaluations, dropped internal traffic and filtered bots don't count. What happens at the cap is set by the owner in **Plans & billing**:

- **Stop** (the default): events stop being stored at the cap (`429 event_limit`). Identify, account, goal and outcome signals sent with a server key keep arriving, up to 10% of the allowance past the cap.
- **Sample down**: from 80% of the allowance, autocapture is kept at a rate falling to zero at the cap. Your own `track` calls are never sampled. Answers carry `pacedOut` when events were held back.
- **Add-on**: at the cap one pre-approved block of 1M events is added, up to the number of blocks the owner approved. Only events sent with a server key can start a block.

When a batch would cross the cap, your own events are kept ahead of autocapture, and the answer carries `sampledDown` with the number left out.

## Send events over HTTP

You don't need an SDK. `POST /api/v1/events` takes one event with a server key that has the `events:write` scope (see [Keys, scopes and environments](https://apphelm.dev/docs/keys-and-environments)).

| Field | Required | Notes |
| --- | --- | --- |
| `workspaceId` | Yes | `org_…`, at most 80 characters |
| `productId` | Yes | `prd_…`; the key must allow this product |
| `eventName` | Yes | At most 100 characters |
| `properties` | No | An object. Put the person's id in `distinct_id` |
| `occurredAt` | No | ISO 8601; defaults to the time it arrived |
| `eventId` | No | 8–64 of `A-Z a-z 0-9 _ -`. Sending the same id again stores nothing and answers `"duplicate": true`, so retries are safe |
| `privacyMode` | No | `aggregate` (default), `consented` or `strict`; a label stored with the event. Any other value is refused with `422 invalid_privacy_mode` |

To send up to 50 events in one request, wrap them in an `apphelm_batch` envelope. Each one counts as its own event; the envelope does not.

```bash
curl -X POST https://apphelm.dev/api/v1/events \
  -H "Authorization: Bearer $APPHELM_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{
    "workspaceId": "org_…", "productId": "prd_…", "eventName": "apphelm_batch",
    "eventId": "nightly-sync-2026-11-07",
    "properties": { "events": [
      { "name": "invoice_paid", "properties": { "distinct_id": "user-123", "amount": 42 }, "occurredAt": "2026-11-07T09:12:00Z" },
      { "name": "invoice_paid", "properties": { "distinct_id": "user-456", "amount": 17 } }
    ] }
  }'
# 202 {"accepted":true,"eventId":"cid:prd_…:nightly-sync-2026-11-07","storedEvents":2}
```

A `202` with `"accepted": false` means the request was valid but nothing was stored, and `reason` says why: `internal_traffic`, `inbound_filter` (an error filter), `autocapture_disabled`, `autocapture_denylisted`, `autocapture_sampled`, `autocapture_dropped` (every event in a batch was), `autocapture_paced` or `event_limit_sampled_out`. Browser requests can also get `bot_filtered`, `collection_paused` or `product_archived` this way. The full schema is in the [API reference](https://apphelm.dev/docs/api).

## Check that it works

### Send one event
Trigger the code once: load the page, tap the button, run the script. For the browser, give analytics consent first.

### Watch it arrive
Run `npx @sansavision/apphelm events tail --product prd_…` with a key that has `analytics:read`. It prints the newest events and then each new one, with the properties AppHelm kept. **Analytics → Delivery receipts** in the app shows the last 30 events received.

### Turn on debug output if nothing arrives
Create the client with `debug: true` (`Debug = true` in .NET, `debug=True` in Python). The SDK then says on the console why it sent nothing: no consent, Global Privacy Control, `enabled: false`, a `beforeSend` drop, or a refused request with its status. It never prints an event's contents.

### Chart it
Open **Analytics**, pick the event and check the count. Events usually appear within seconds.

## Best practices

- **Track outcomes on the server when you can.** A server event can't be blocked by an ad blocker or lost when a tab closes. Send `invoice_paid` from your billing code, and let the browser record the journey.
- **Use one distinct id per person everywhere**: your user id after sign-in. Then web, mobile and server events join up.
- **Keep property values bounded.** A property with a few hundred values (plan, country, format) breaks down well. One with millions (an order id) does not; send ids only when you need to filter on one.
- **Flush before exit** in scripts, serverless functions and jobs.
- **Never send secrets or personal data as properties.** AppHelm scrubs what it recognises, but a name or a free-text field it does not recognise is stored as sent.

## Troubleshooting

| Symptom | Likely cause | What to do |
| --- | --- | --- |
| Nothing arrives from the browser | No analytics consent yet, Global Privacy Control is on, or `enabled: false` | Call `setConsent({ analytics: true })` after the person agrees; turn on `debug: true` to see the reason |
| Browser requests fail with `401 invalid_project_key` | The page's origin is not in the key's allowed origins, or the key is not a browser key (`ahl_pub_…`) | Add the exact origin (scheme, host and port) to the key in Settings, or use the product's browser key |
| `403 scope_denied` from the API | The server key lacks `events:write` | Create a key with `events:write` for this product |
| `403 scope_mismatch` | The `workspaceId` or `productId` doesn't match the key | Use the ids shown for the key in Settings, or a key that allows that product |
| `403 server_authority_required` | An `apphelm.*` customer signal was sent with a browser key | Send customer signals from your server with a server key |
| `422 missing_fields` | `workspaceId`, `productId` or `eventName` missing, or the name is over 100 characters | Fill in all three and shorten the name |
| `422 invalid_privacy_mode` | `privacyMode` is not `aggregate`, `consented` or `strict` | Use one of the three, or leave it out |
| `429 event_limit` | The monthly allowance is used up | Raise the plan, choose sample-down or add-on in **Plans & billing**, or cut autocapture |
| `409 collection_paused` or `product_archived` | Collection is paused for the workspace, or the product is archived | Resume collection in **Settings → Capture**, or restore the product |
| A property is missing from charts | Its key looks sensitive, it is nested, or it came after the first 20 | Rename it, flatten it, or send fewer properties |
| Server events don't join the person's browser events | Different ids: the browser is anonymous or uses another id | Identify the browser with your user id and use the same id on the server ([Users, people and groups](https://apphelm.dev/docs/identify)) |
| Backdated events show on today | Charts use the time AppHelm received the event | Send history with `apphelm_import: true` from a server key |
| The last events of a script never arrive | The process exited before the queue was sent | Call `flush`, `close` or `shutdown` before exit |
