Get started

Install and configure

Install the AppHelm SDK on any of 18 platforms, then set the options that matter in production - environment, release, consent, sampling, autocapture, replay, error capture, debug output and shutdown.

Markdown

This page installs the SDK for your platform and explains every option you are likely to change. Choose your platform in the Language menu in the sidebar: the install steps, option tables and code below change to match it.

If you only want a first event, the Quickstart is shorter. If you want a coding assistant to do this for you, see Set up with AI.

#Before you start

You need three things from AppHelm. Setup (/app/onboarding) gives you all of them.

What Looks like Where it goes
Workspace id org_… In the SDK options. Not secret.
Product id prd_… In the SDK options. Not secret. One product is one app, site or service.
A key ahl_pub_… or ahl_live_… Depends on where the code runs (below).

Which key you use depends on where the code runs:

Code runs in Key Why
A browser (Next.js, React, Vue, Svelte, Angular, plain HTML) Browser key, ahl_pub_… Public by design. It only accepts requests whose Origin is one you allowed for it.
A mobile app (React Native, iOS, Android, Flutter) A server key with only events:write Anything in an app binary can be extracted, so the key must be able to do nothing but send events and evaluate flags. Setup creates exactly this key for mobile platforms.
A server (Node, Python, JVM, Go, Ruby, PHP, .NET, Rust, Elixir) Server key, ahl_live_… Secret. Keep it in an environment variable or secret manager, never in client code or git.

Keys, scopes and environments explains scopes, origins, rotation and staging.

#Install the SDK

These are the same steps the Setup wizard, npx @sansavision/apphelm init and the docs MCP server's get_install_plan produce. In Setup, your own ids and keys are filled in.

Next.js

Install:

npm install @sansavision/apphelm

Environment:

NEXT_PUBLIC_APPHELM_KEY=<your browser key, ahl_pub_…>
APPHELM_API_KEY=<your server key, ahl_live_…>
  • NEXT_PUBLIC_APPHELM_KEY: Browser key. Public by design: it only sends events from the origins you allowed for it.

  • APPHELM_API_KEY: Server key. Keep it secret: server environment only, never in browser code, an app binary or git.

A client component that starts the browser SDK. The browser SDK sends nothing until the visitor gives analytics consent: call setConsent({ analytics: true }) from your consent banner (or pass consent in the options when you have it already).

app/apphelm-provider.tsx
"use client";
import { ApphelmProvider } from "@sansavision/apphelm/react";

export function AppHelm({ children }: { children: React.ReactNode }) {
  return (
    <ApphelmProvider options={{
      key: process.env.NEXT_PUBLIC_APPHELM_KEY!,
      workspaceId: "org_…",
      productId: "prd_…",
    }}>
      {children}
    </ApphelmProvider>
  );
}

Wrap the app in the provider (merge into your existing root layout).

app/layout.tsx
import { AppHelm } from "./apphelm-provider";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return <html lang="en"><body><AppHelm>{children}</AppHelm></body></html>;
}

Server-side events (route handlers, server actions). Reads the server key from the environment; never import this file from a client component.

lib/apphelm.ts
// Server only: never import this file from a client component.
import { Apphelm } from "@sansavision/apphelm";

export const apphelm = new Apphelm({
  apiKey: process.env.APPHELM_API_KEY!,
  workspaceId: "org_…",
  productId: "prd_…",
});

// await apphelm.capture({ distinctId: user.id, event: "signup_completed" });

Check: Load a page (or run the code) once, then press Check connection: the first event appears within a few seconds.

React

Install:

npm install @sansavision/apphelm

Environment:

VITE_APPHELM_KEY=<your browser key, ahl_pub_…>
  • VITE_APPHELM_KEY: Browser key. Public by design: it only sends events from the origins you allowed for it.

Wrap your app in the provider (merge into your entry file). With Create React App use process.env.REACT_APP_APPHELM_KEY instead. The browser SDK sends nothing until the visitor gives analytics consent: call setConsent({ analytics: true }) from your consent banner (or pass consent in the options when you have it already).

src/main.tsx
import { createRoot } from "react-dom/client";
import { ApphelmProvider } from "@sansavision/apphelm/react";
import App from "./App";

createRoot(document.getElementById("root")!).render(
  <ApphelmProvider options={{
    key: import.meta.env.VITE_APPHELM_KEY,
    workspaceId: "org_…",
    productId: "prd_…",
  }}>
    <App />
  </ApphelmProvider>,
);

Check: Load a page (or run the code) once, then press Check connection: the first event appears within a few seconds.

Vue / Nuxt

Install:

npm install @sansavision/apphelm

Environment:

VITE_APPHELM_KEY=<your browser key, ahl_pub_…>
  • VITE_APPHELM_KEY: Browser key. Public by design: it only sends events from the origins you allowed for it.

Import it once from src/main.ts (Nuxt: a client-only plugin, plugins/apphelm.client.ts, reading useRuntimeConfig().public.apphelmKey). The browser SDK sends nothing until the visitor gives analytics consent: call setConsent({ analytics: true }) from your consent banner (or pass consent in the options when you have it already).

src/apphelm.ts
import { createBrowserSdk } from "@sansavision/apphelm/browser";

export const apphelm = createBrowserSdk({
  key: import.meta.env.VITE_APPHELM_KEY,
  workspaceId: "org_…",
  productId: "prd_…",
});

// From your consent banner:
// apphelm.setConsent({ analytics: true });
// apphelm.track({ name: "signup_completed" });

Check: Load a page (or run the code) once, then press Check connection: the first event appears within a few seconds.

Svelte / SvelteKit

Install:

npm install @sansavision/apphelm

Environment:

VITE_APPHELM_KEY=<your browser key, ahl_pub_…>
  • VITE_APPHELM_KEY: Browser key. Public by design: it only sends events from the origins you allowed for it.

Import it once from your root layout in the browser only (SvelteKit: src/routes/+layout.svelte inside onMount, reading PUBLIC_APPHELM_KEY from $env/static/public). The browser SDK sends nothing until the visitor gives analytics consent: call setConsent({ analytics: true }) from your consent banner (or pass consent in the options when you have it already).

src/lib/apphelm.ts
import { createBrowserSdk } from "@sansavision/apphelm/browser";

export const apphelm = createBrowserSdk({
  key: import.meta.env.VITE_APPHELM_KEY,
  workspaceId: "org_…",
  productId: "prd_…",
});

// From your consent banner:
// apphelm.setConsent({ analytics: true });
// apphelm.track({ name: "signup_completed" });

Check: Load a page (or run the code) once, then press Check connection: the first event appears within a few seconds.

Plain HTML

Paste before on every page. The browser key is public, so it can sit in the page. The browser SDK sends nothing until the visitor gives analytics consent: call setConsent({ analytics: true }) from your consent banner (or pass consent in the options when you have it already).

index.html
<script type="module">
  import { createBrowserSdk } from "https://cdn.jsdelivr.net/npm/@sansavision/apphelm/dist/browser.js";
  window.apphelm = createBrowserSdk({
    key: "<your browser key, ahl_pub_…>",
    workspaceId: "org_…",
    productId: "prd_…",
  });
  // From your consent banner: window.apphelm.setConsent({ analytics: true });
</script>

Check: Load a page (or run the code) once, then press Check connection: the first event appears within a few seconds.

Node.js

Install:

npm install @sansavision/apphelm

Environment:

APPHELM_API_KEY=<your server key, ahl_live_…>
  • APPHELM_API_KEY: Server key. Keep it secret: server environment only, never in browser code, an app binary or git.

Server-side events. Use your user id as distinctId so server and browser events join.

src/apphelm.ts
import { Apphelm } from "@sansavision/apphelm";

export const apphelm = new Apphelm({
  apiKey: process.env.APPHELM_API_KEY!,
  workspaceId: "org_…",
  productId: "prd_…",
});

// await apphelm.capture({ distinctId: user.id, event: "signup_completed" });

Check: Run the code once (for example with a capture call at startup), then press Check connection.

React Native / Expo

Install:

npm install @sansavision/apphelm @react-native-async-storage/async-storage

Environment:

EXPO_PUBLIC_APPHELM_KEY=<an events:write-only key, ahl_live_…>
  • EXPO_PUBLIC_APPHELM_KEY: Ships inside the app, so anyone can extract it: create a key with the events:write scope only (Settings → API keys).

Create the client once and import it where you track. Without Expo, pass the key from your config library instead of process.env.

apphelm.ts
import AsyncStorage from "@react-native-async-storage/async-storage";
import { AppState } from "react-native";
import { createReactNativeSdk } from "@sansavision/apphelm/react-native";

export const apphelm = createReactNativeSdk({
  apiKey: process.env.EXPO_PUBLIC_APPHELM_KEY!,
  workspaceId: "org_…",
  productId: "prd_…",
  storage: AsyncStorage,
  appState: AppState,
});

// apphelm.screen("Home");

Check: Open the app once, then press Check connection: $app_opened arrives first.

iOS (Swift)

Install:

.package(url: "https://github.com/Sansa-Organisation/apphelm-swift.git", from: "0.8.1")

Add the package in Xcode (File → Add Package Dependencies) with the URL above, product Apphelm. The key ships inside the app: give it the events:write scope only.

AppHelm.swift
import Apphelm

let apphelm = ApphelmClient(options: ApphelmOptions(
  apiKey: "<an events:write-only key, ahl_live_…>",
  workspaceId: "org_…",
  productId: "prd_…"
))

// apphelm.track("signup_completed")

Check: Launch the app once, then press Check connection: lifecycle events arrive on their own.

Android (Kotlin)

Install:

implementation("com.sansavision:apphelm-android:0.8.1")

Environment:

APPHELM_API_KEY=<an events:write-only key, ahl_live_…>
  • APPHELM_API_KEY: Read at build time into BuildConfig. It ships inside the app: give it the events:write scope only.

Add to the android block so the key reaches BuildConfig, and the dependency above to dependencies.

app/build.gradle.kts
android {
    buildFeatures { buildConfig = true }
    defaultConfig {
        buildConfigField("String", "APPHELM_API_KEY", "\"${System.getenv("APPHELM_API_KEY") ?: ""}\"")
    }
}

Set up once from your Application class (register it in AndroidManifest.xml with android:name).

app/src/main/kotlin/App.kt
import android.app.Application
import apphelm.android.Apphelm
import apphelm.android.ApphelmConfig

class App : Application() {
    override fun onCreate() {
        super.onCreate()
        Apphelm.setup(this, ApphelmConfig(BuildConfig.APPHELM_API_KEY, "org_\u2026", "prd_\u2026"))
    }
}

Check: Launch the app once, then press Check connection: $app_opened arrives first.

Python

Install:

pip install apphelm

Environment:

APPHELM_API_KEY=<your server key, ahl_live_…>
  • APPHELM_API_KEY: Server key. Keep it secret: server environment only, never in browser code, an app binary or git.

Server-side events. Python 3.10 or later, standard library only.

apphelm_client.py
import os
from apphelm import Apphelm

apphelm = Apphelm(api_key=os.environ["APPHELM_API_KEY"])
WORKSPACE_ID = "org_…"
PRODUCT_ID = "prd_…"

# apphelm.capture(WORKSPACE_ID, PRODUCT_ID, distinct_id=user.id, event_name="signup_completed")

Check: Run a capture call once, then press Check connection.

Java / Kotlin (JVM)

Install:

implementation("com.sansavision:apphelm:0.8.1")

Environment:

APPHELM_API_KEY=<your server key, ahl_live_…>
  • APPHELM_API_KEY: Server key. Keep it secret: server environment only, never in browser code, an app binary or git.

Server-side events from a JVM service (Kotlin or Java 17+). Share one client and close() it on shutdown.

src/main/kotlin/Apphelm.kt
import apphelm.ApphelmClient
import apphelm.ApphelmOptions

val apphelm = ApphelmClient(ApphelmOptions(
    apiKey = System.getenv("APPHELM_API_KEY"),
    workspaceId = "org_\u2026",
    productId = "prd_\u2026",
))

// apphelm.track("report_exported")

Check: Run a track call once, then press Check connection.

Go

Install:

go get apphelm.dev/go@v0.8.1

Environment:

APPHELM_API_KEY=<your server key, ahl_live_…>
  • APPHELM_API_KEY: Server key. Keep it secret: server environment only, never in browser code, an app binary or git.

Server-side events, Go 1.21 or later, standard library only. Change the package name to put it elsewhere. If your network cannot reach the public Go proxy, set GOPROXY=https://apphelm.dev/packages/go,https://proxy.golang.org,direct (and GONOSUMDB=apphelm.dev/go if the checksum database is unreachable too).

apphelm.go
package main

import (
	"os"

	apphelm "apphelm.dev/go"
)

// newApphelm creates the one client the app shares. In main:
//
//	client, err := newApphelm()
//	if err != nil {
//		log.Fatal(err)
//	}
//	defer client.Close() // sends what is still queued
//
//	client.Capture(apphelm.Capture{DistinctID: user.ID, Event: "signup_completed"})
func newApphelm() (*apphelm.Client, error) {
	return apphelm.New(apphelm.Config{
		APIKey:      os.Getenv("APPHELM_API_KEY"),
		WorkspaceID: "org_\u2026",
		ProductID:   "prd_\u2026",
	})
}

Check: Run a Capture call once, then press Check connection.

Ruby

Add the package source first:

Add to your Gemfile, then run the install command. The source block makes Bundler take apphelm from apphelm.dev only, never from another source. Without Bundler: gem install apphelm --source https://apphelm.dev/packages/ruby

Gemfile
source "https://apphelm.dev/packages/ruby" do
  gem "apphelm", "~> 0.8"
end

Install:

bundle install

Environment:

APPHELM_API_KEY=<your server key, ahl_live_…>
  • APPHELM_API_KEY: Server key. Keep it secret: server environment only, never in browser code, an app binary or git.

Server-side events, Ruby 3.1 or later. Rails loads config/initializers on boot; elsewhere, require this file once at startup. Thread-safe and fork-safe.

config/initializers/apphelm.rb
require "apphelm"

APPHELM = Apphelm::Client.new(
  api_key: ENV.fetch("APPHELM_API_KEY"),
  workspace_id: "org_\u{2026}",
  product_id: "prd_\u{2026}"
)
at_exit { APPHELM.shutdown } # sends what is still queued

# APPHELM.capture(distinct_id: user.id, event: "signup_completed")

Check: Run a capture call once, then press Check connection.

PHP

Install:

composer config repositories.apphelm composer https://apphelm.dev/packages/composer
composer require sansavision/apphelm

Environment:

APPHELM_API_KEY=<your server key, ahl_live_…>
  • APPHELM_API_KEY: Server key. Keep it secret: server environment only, never in browser code, an app binary or git.

Server-side events, PHP 8.1 or later. Load Composer's vendor/autoload.php first (Laravel and Symfony already do). Each event is sent during the call that makes it; in a long-running worker (Octane, RoadRunner, Swoole) call $apphelm->flush() after each job or request.

apphelm.php
<?php

use Apphelm\Client;

$apphelm = new Client(
    apiKey: getenv('APPHELM_API_KEY'),
    workspaceId: 'org_…',
    productId: 'prd_…',
);

// $apphelm->capture(distinctId: (string) $user->id, event: 'signup_completed');

Check: Run a capture call once, then press Check connection.

Flutter

Install:

flutter pub add apphelm_flutter --hosted-url https://apphelm.dev/packages/pub

Environment:

APPHELM_KEY=<an events:write-only key, ahl_live_…>
  • APPHELM_KEY: Passed at build time: flutter run --dart-define=APPHELM_KEY=… (the same for flutter build). It ships inside the app, so anyone can extract it: give it the events:write scope only.

Set up once before runApp (merge into your main.dart). Pure Dart, so the same code runs on iOS, Android, web and desktop. Its dependencies (http, shared_preferences) still come from pub.dev.

lib/main.dart
import 'package:flutter/material.dart';
import 'package:apphelm_flutter/apphelm_flutter.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Apphelm.setup(ApphelmConfig(
    apiKey: const String.fromEnvironment('APPHELM_KEY'), // events:write only
    workspaceId: 'org_\u{2026}',
    productId: 'prd_\u{2026}',
  ));
  runApp(const MyApp()); // add ApphelmObserver() to your MaterialApp's navigatorObservers for screen views
}

// Apphelm.instance.track('signup_completed');

Check: Launch the app once, then press Check connection: $app_opened arrives first.

.NET

Install:

dotnet new nugetconfig    # only if the solution has no nuget.config yet
dotnet nuget add source https://apphelm.dev/packages/nuget/index.json --name apphelm --configfile nuget.config
dotnet add package SansaVision.Apphelm

Environment:

APPHELM_API_KEY=<your server key, ahl_live_…>
  • APPHELM_API_KEY: Server key. Keep it secret: server environment only, never in browser code, an app binary or git.

Server-side events, .NET 8 or .NET Standard 2.0. Keep nuget.org in nuget.config too: the package depends on Microsoft packages from there. In ASP.NET Core, add SansaVision.Apphelm.AspNetCore and call builder.Services.AddApphelm(…) instead, which registers one client and flushes it when the host stops.

Program.cs
using Apphelm;

// One client for the whole app. Disposing it sends what is still queued.
await using var apphelm = new ApphelmClient(new ApphelmOptions
{
    ApiKey = Environment.GetEnvironmentVariable("APPHELM_API_KEY")!,
    WorkspaceId = "org_\u2026",
    ProductId = "prd_\u2026",
});

// apphelm.Capture(user.Id, "signup_completed");

Check: Run a Capture call once, then press Check connection.

Elixir

Add the package source first:

Add to your deps. The repository must be named apphelm; its key fingerprint (mix hex.repo list) is SHA256:jokXz/stsZM7KS9JSjA27c12iygbBwVqIh7587t3NEs. jason and plug still come from hex.pm.

mix.exs
def deps do
  [{:apphelm, "~> 0.8.1", repo: "apphelm"}]
end

Install:

curl -fsSo apphelm_hex.pem https://apphelm.dev/packages/hex/public_key
mix hex.repo add apphelm https://apphelm.dev/packages/hex --public-key apphelm_hex.pem
mix deps.get

Environment:

APPHELM_API_KEY=<your server key, ahl_live_…>
  • APPHELM_API_KEY: Server key. Keep it secret: server environment only, never in browser code, an app binary or git.

Server-side events, Elixir 1.14 or later. Merge into config/runtime.exs: with :api_key set, the :apphelm application starts the client itself. Add the repository in CI too, before mix deps.get.

config/runtime.exs
import Config

config :apphelm,
  api_key: System.fetch_env!("APPHELM_API_KEY"),
  workspace_id: "org_\u{2026}",
  product_id: "prd_\u{2026}"

# Apphelm.capture(user.id, "signup_completed")

Check: Start the app, run Apphelm.capture once, then press Check connection.

Rust

Add the package source first:

Names the apphelm.dev registry, in your project (or ~/.cargo/config.toml). Then the install command adds apphelm = { version = "0.8", registry = "apphelm" } to Cargo.toml; add features = ["async"] for tokio applications.

.cargo/config.toml
[registries.apphelm]
index = "sparse+https://apphelm.dev/packages/cargo/"

Install:

cargo add apphelm --registry apphelm

Environment:

APPHELM_API_KEY=<your server key, ahl_live_…>
  • APPHELM_API_KEY: Server key. Keep it secret: server environment only, never in browser code, an app binary or git.

Server-side events, Rust 1.82 or later. Add mod apphelm_client; to main.rs, create the client at startup and clone it where you capture (clones share one queue).

src/apphelm_client.rs
use apphelm::{Client, Options};

/// The one client the app shares. Call `shutdown()` before the process exits: it sends what is still queued.
pub fn connect() -> Result<Client, Box<dyn std::error::Error>> {
    let options = Options::new(std::env::var("APPHELM_API_KEY")?)
        .workspace_id("org_\u{2026}")
        .product_id("prd_\u{2026}");
    Ok(Client::new(options)?)
}

// apphelm.capture(apphelm::Event::new(&user.id, "signup_completed"))?;

Check: Run a capture call once, then press Check connection.

HTTP

There is no SDK to install. Send events from a server with a server key that has events:write:

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":"signup_completed","properties":{"distinct_id":"user-123"}}'

A request body is at most 64,000 bytes. The answer is 202 with { "accepted": true, "eventId": … }. Send an eventId of your own to make retries safe: an event id AppHelm has already stored is answered 202 with duplicate: true and stored once. The API reference lists every endpoint.

#Check that it works

  1. Run the code once

    Load a page, open the app, or run a capture call on the server.

  2. Press Check connection

    In Setup, Check connection looks for the newest event that reached the product and shows it. Events usually arrive within seconds. Setup also lists what is still missing: events arriving, the browser SDK sending, events that carry a person's id, customer profiles, an approved outcome, alerts and an issue tracker. Each item links to the page that fixes it.

  3. Turn on debug output if nothing arrives

    Every SDK can say why it is not sending. Turn it on in development only; it never prints event contents.

No example for this step; showing Next.js.

<ApphelmProvider options={{ key, workspaceId, productId, debug: true }}>
// Console: "[AppHelm] waiting for analytics consent…" or "[AppHelm] POST /api/events was refused: 401"
<ApphelmProvider options={{ key, workspaceId, productId, debug: true }}>
// Console: "[AppHelm] waiting for analytics consent…" or "[AppHelm] POST /api/events was refused: 401"
export const apphelm = createBrowserSdk({ key, workspaceId, productId, debug: true });
export const apphelm = createBrowserSdk({ key, workspaceId, productId, debug: true });
window.apphelm = createBrowserSdk({ key, workspaceId, productId, debug: true }); // console.warn lines prefixed [AppHelm]
const apphelm = new Apphelm({ apiKey, workspaceId, productId, debug: true }); // console.warn lines prefixed [AppHelm]
var options = ApphelmOptions(apiKey: key, workspaceId: "org_…", productId: "prd_…")
options.debug = true // unified log, subsystem dev.apphelm, category sdk
Apphelm.setup(this, ApphelmConfig(BuildConfig.APPHELM_API_KEY, "org_…", "prd_…").apply {
    debug = BuildConfig.DEBUG // Logcat, tag "Apphelm"
})
await Apphelm.setup(ApphelmConfig(apiKey: key, workspaceId: 'org_…', productId: 'prd_…', debug: true)); // debugPrint
val apphelm = ApphelmClient(ApphelmOptions(apiKey = key, workspaceId = "org_…", productId = "prd_…", debug = true)) // stderr, or debugLogger
apphelm.init(api_key=os.environ["APPHELM_API_KEY"], workspace_id="org_…", product_id="prd_…", debug=True)  # stderr
client, err := apphelm.New(apphelm.Config{APIKey: key, WorkspaceID: "org_…", ProductID: "prd_…", Debug: true}) // DebugWriter, default os.Stderr
APPHELM = Apphelm::Client.new(api_key: ENV.fetch("APPHELM_API_KEY"), workspace_id: "org_…", product_id: "prd_…", debug: true) # $stderr, "[apphelm] …"
$apphelm = new Client(apiKey: getenv('APPHELM_API_KEY'), workspaceId: 'org_…', productId: 'prd_…', debug: true); // error_log, or debugOutput
var apphelm = new ApphelmClient(new ApphelmOptions { ApiKey = key, WorkspaceId = "org_…", ProductId = "prd_…", Debug = true }); // stderr, or DiagnosticLogger
let options = Options::new(key).workspace_id("org_…").product_id("prd_…").debug(true); // stderr, "[apphelm] …"
config :apphelm, api_key: System.fetch_env!("APPHELM_API_KEY"), workspace_id: "org_…", product_id: "prd_…", debug: true # Logger, :info

The React Native SDK has no debug option. Use onCapture((name, properties) => …) to see each event as it is queued, and check the network inspector for requests to /api/v1/events.

If the debug output does not explain it, see Troubleshooting.

#Options every SDK shares

The names differ per language (tracesSampleRate, traces_sample_rate, TracesSampleRate), but the meaning is the same everywhere.

Option Default What it does
Key, workspace id, product id required Who is sending and where events go.
environment not set A label such as production or staging, sent with errors, transactions, sessions and logs. At most 40 characters. In the browser it also picks a flag's rollout for that environment; Keys, scopes and environments shows how each SDK passes it to flags.
release not set, except Android Your build's version, such as shop@2.4.0. Links errors to uploaded source maps and symbols, powers release health and "resolve in next release". At most 120 characters. Android defaults it to versionName+versionCode.
enabled true false sends nothing at all. Flag reads keep working. Use it in tests.
debug false The SDK's own diagnostics: why something was dropped, and requests AppHelm refused, with the status. Never event contents.
sampleRate 1 The share of errors and messages sent. It does not apply to analytics events.
tracesSampleRate not set The share of traces kept. While it is not set, automatic tracing (page loads, requests, screen loads) sends nothing; transactions you start yourself are kept.
profilesSampleRate not set (off) The share of sampled transactions that are also profiled.
beforeSend none Change an event, or return null to drop it. A hook that throws drops the event, so a failing scrubber never lets data through.
ignoreErrors, denyUrls, allowUrls, ignoreTransactions empty Drop errors by message or by the file they were thrown in, and transactions by name, before anything leaves the process.
Base URL (endpoint in the browser, baseUrl, base_url, BaseURL) https://apphelm.dev Where requests go.

#Options for your platform

Browser SDK (createBrowserSdk, and the options of every web framework provider)

Option Default What it does
key, workspaceId, productId required The browser key and the product.
consent { analytics: false, replay: false } The consent you already have at start-up. Nothing is recorded or sent until analytics is true. See Consent and opt-out.
enabled true false records and sends nothing, whatever setConsent says. Flags still load.
distinctId a stored random id Your user id, when you know it at start-up.
autocapture true Page views (also on pushState navigation), page leave with scroll depth, clicks, form submits and changes, and web vitals. What is typed into a field is never sent, and password, email, phone and card fields are skipped entirely.
errorCapture true Uncaught errors and unhandled promise rejections, once analytics consent exists.
errorContext false Automatic breadcrumbs, the page path and browser and OS tags on exceptions.
maxBreadcrumbs 20 Breadcrumbs per error, 0 to 100.
release, environment not set Sent with exceptions; environment also picks a flag's environment rollout.
releaseHealth false One $session per page load, for crash-free rates. Needs release.
tracesSampleRate not set Page-load and navigation transactions are recorded only when set.
tracePropagationTargets the page's own origin Where fetch sends traceparent and baggage. Your API must allow those headers in CORS.
profilesSampleRate off Profiles of traced page loads. Needs the page served with Document-Policy: js-profiling (Chromium browsers).
replay DOM recording, every input masked Session replay options: sampleRate (default 1), onErrorSampleRate, maskAllText, blockedPaths, linkedFlag and more. Records only with replay consent.
beforeSend none Change or drop each event at send time. Replay is not affected.
sampleRate, ignoreErrors, denyUrls, allowUrls, ignoreTransactions 1, empty Error and transaction filters, applied in the browser.
attachStacktrace false captureMessage also sends the stack of the call.
initialScope none Tags, contexts, level and fingerprint every exception starts with.
bootstrap none Flags evaluated on your server, used until the first load, so flags never flicker.
logsMinLevel, logsService, beforeSendLog "info", "browser", none For apphelm.logger. See Logs.
flushIntervalMs 5000 How often the queue is sent (at least 1,000).
maxBatchSize 20 Events per request (at most 50). A full batch is sent at once.
maxQueueSize, maxQueueBytes 100, 48000 The in-memory queue (at most 500 events and 60,000 bytes). The oldest events go first.
endpoint https://apphelm.dev The base URL.
debug false Diagnostics with console.warn, prefixed [AppHelm].

The core script stays within 7,680 bytes gzipped. Autocapture, error capture, tracing, replay, logs, surveys and the toolbar are separate modules, loaded only when they are needed.

Node.js (new Apphelm({ … }) from @sansavision/apphelm)

Option Default What it does
apiKey required A server key.
workspaceId, productId not set Needed for events; you can also pass them per call.
baseUrl https://apphelm.dev
timeoutMs 10000 Per request.
release, environment not set Sent with exceptions, messages, transactions and logs.
tracesSampleRate, tracesSampler not set Automatic request transactions are off until one is set. Transactions you start yourself are kept at a rate of 1 until then.
profilesSampleRate off V8 CPU profiles of sampled transactions. See Profiling.
beforeSend none Sees every event (captures, identify, exceptions, transactions, flag exposures, LLM events).
sampleRate, ignoreErrors, denyUrls, allowUrls, ignoreTransactions 1, empty Error and transaction filters.
maxBreadcrumbs, beforeBreadcrumb 30, none Per scope, process-wide.
attachStacktrace, initialScope false, none As in the browser; initialScope.user is sent as a hash only.
service, logsMinLevel, beforeSendLog none, "info", none For apphelm.logger.
enabled, debug true, false As above. debug writes with console.warn.
fetch globalThis.fetch Your own fetch.

The Node client has no queue: each capture is one request, made when you call it. A refused request rejects with an ApphelmError that carries status, code and requestId. Uncaught exceptions and unhandled rejections are reported only after apphelm.captureUnhandled(), because the same client is also used by scripts and the CLI.

React Native (createReactNativeSdk from @sansavision/apphelm/react-native)

Option Default What it does
apiKey, workspaceId, productId required An events:write-only key.
storage memory Where the queue and ids are kept. Pass AsyncStorage so events survive restarts.
appState none React Native's AppState: the queue is sent when the app goes to the background, and $app_opened/$app_backgrounded are recorded.
flushAt, flushInterval, maxQueueSize 20, 30000 ms, 1000 When the queue is sent, and how many events wait at most.
captureAppLifecycleEvents true $app_installed, $app_updated (need storage), $app_opened, $app_backgrounded (need appState).
appVersion, appBuild, appInfo not set The app's version for lifecycle events and every event; appInfo can read it from expo-application.
defaultOptIn true false starts opted out until optIn(). A stored choice wins.
release, environment, dist not set Sent with exceptions, transactions and sessions.
captureUnhandled true Uncaught errors (ErrorUtils) and unhandled promise rejections. A fatal error waits up to fatalFlushTimeoutMs (2,000) for its report.
enableAutoSessionTracking, sessionTrackingIntervalMillis true, 30000 Release-health sessions. Need release.
tracesSampleRate 0 The share of screens sent as transactions.
instrumentFetch, tracePropagationTargets false, none http.client spans and breadcrumbs for fetch, and where traceparent goes.
sampleRate, ignoreErrors, denyUrls, allowUrls, ignoreTransactions 1, empty Filters.
maxBreadcrumbs, beforeBreadcrumb, beforeSend, initialScope 30, none As in the browser.
profiling, replay none hermesProfiling(…) and mobileReplay(…); see Profiling and Session replay.
surveyKey, surveyOrigin none A browser key and one of its origins, for surveys and replay uploads.
baseUrl https://apphelm.dev

iOS and macOS (ApphelmOptions; iOS 16 or macOS 13 and later)

Option Default What it does
apiKey, workspaceId, productId required An events:write-only key.
baseURL, timeoutSeconds https://apphelm.dev, 10
release, environment not set Sent with exceptions, crashes and sessions.
flushIntervalSeconds, flushAt, flushOnBackground 30, 20, true When the queue is sent.
maxQueueSize, persistence 1000, .disk The queue lives on disk, so events survive the app being killed. .memory writes nothing.
captureApplicationLifecycleEvents true Install, update, open and background events.
captureScreenViews true A $screen for each UIKit view controller. SwiftUI uses .apphelmScreen("Name").
defaultOptedOut false Start opted out until optIn().
enableAutoSessionTracking, sessionTrackingIntervalSeconds true, 30 Release health. Needs release.
tracesSampleRate, tracesSampler not set Automatic screen-load and app-start tracing is off until set.
enableUIViewControllerTracing, enableAppStartTracking false, false Screen loads (TTID) and app starts, with a rate set.
enableAppHangTracking, appHangTimeoutInterval true, 2 s App hangs, started by installCrashReporting().
enableNetworkTracking, enableNetworkBreadcrumbs, enableFileIOTracing, enableCoreDataTracing, enableSwizzling true Automatic spans and breadcrumbs.
profilesSampleRate off
replay off ReplayOptions; records only after setReplayConsent(true).
maxBreadcrumbs, beforeBreadcrumb, beforeSend 100, none Each event carries the last 30 breadcrumbs.
sampleRate, ignoreErrors, denyUrls, allowUrls, ignoreTransactions 1, empty Filters.
enabled, debug true, false debug writes to the unified log.

Crash capture is not automatic: call installCrashReporting() once early in launch and then sendPendingCrashReports(). See Crashes, ANRs and app hangs.

Android (ApphelmConfig, Android 8 / API 26 and later)

Option Default What it does
apiKey, workspaceId, productId required An events:write-only key, from BuildConfig.
baseUrl, timeoutMs https://apphelm.dev, 10000
release, build, environment versionName+versionCode, version code, not set
captureApplicationLifecycleEvents, captureScreenViews, screenName true, true, none A $screen per Activity; screenName names them.
captureCrashes, captureNativeCrashes, captureAnrs, anrTimeoutMs true, true, true, 5000 Crashes and ANRs, sent on the next launch.
startSessions, sessionTimeoutMs true, 30000 Release health.
tracesSampleRate, tracesSampler not set Screen loads, app starts and frame metrics need one.
profilesSampleRate off
preloadFeatureFlags, flagsEnvironment true, not set Load every flag at setup for the non-blocking isFeatureEnabled; the environment flags are evaluated for.
flushIntervalMs, flushAt, maxQueueSize 30000, 20, 1000 The queue is on disk under filesDir/apphelm/<productId>/queue.
optOut false Start opted out until Apphelm.optIn().
replay off Records only after Apphelm.setReplayConsent(true).
maxBreadcrumbs, beforeBreadcrumb, captureTapBreadcrumbs, beforeSend 100, none, true, none
sampleRate, ignoreErrors, denyUrls, allowUrls, ignoreTransactions 1, empty Filters.
enabled, debug true, false debug writes to Logcat, tag Apphelm.

Flutter (ApphelmConfig)

Option Default What it does
apiKey, workspaceId, productId required An events:write-only key, passed with --dart-define.
baseUrl, requestTimeout https://apphelm.dev, 10 s
storage SharedPreferencesStorage Where the queue and ids are kept. MemoryStorage keeps nothing.
flushAt, flushInterval, maxQueueSize, flushOnBackground 20, 30 s, 1000, true
captureApplicationLifecycleEvents true
appVersion, appBuild, appInfo not set Without them lifecycle events carry no version.
defaultOptIn true
preloadFeatureFlags, flagsEnvironment true, not set
release, environment not set
captureFlutterErrors false FlutterError.onError, PlatformDispatcher.onError and isolate errors. Apphelm.init(…, appRunner:) turns it on.
tracesSampleRate, tracesSampler, tracePropagationHosts not set
enableAutoSessionTracking, sessionTrackingInterval true, 30 s
maxBreadcrumbs, beforeBreadcrumb, beforeSend 100, none
sampleRate, ignoreErrors, denyUrls, allowUrls, ignoreTransactions 1, empty
replay, integrations none Wireframe replay; optional packages such as ApphelmNativeIntegration().
enabled, debug true, false debug prints with debugPrint.

Native crashes, ANRs and app hangs need the apphelm_flutter_native package. See Crashes, ANRs and app hangs.

JVM (ApphelmOptions, Kotlin or Java 17+)

Option Default What it does
apiKey, workspaceId, productId required A server key.
baseUrl, timeoutMs https://apphelm.dev, 10000
release, environment, build not set
flushIntervalMs, flushAt, maxQueueSize 30000, 20, 100 Sent from a daemon thread.
storageDirectory memory Keep ids and the queue on disk.
tracesSampleRate, tracePropagationHosts not set, empty
profilesSampleRate off
maxBreadcrumbs, beforeBreadcrumb, beforeSend 100, none
sampleRate, enabled, debug, debugLogger 1, true, false, stderr

withRequest (or startRequest in Java) gives a request its scope and transaction. Crash capture of uncaught exceptions is opt-in with installCrashReporting(store).

Python (apphelm.init(…) for apps and workers, or Apphelm(…) as a plain client; Python 3.10+)

Option Default What it does
api_key, workspace_id, product_id required for init
base_url, timeout_seconds https://apphelm.dev, 10.0
release, environment not set
background True with init, False on Apphelm(…) Send from a background thread (queue of 1,000; a full queue drops). atexit flushes it.
capture_unhandled True init reports uncaught exceptions.
logging_breadcrumbs True logging records at warning and above become breadcrumbs.
traces_sample_rate, traces_sampler, trace_propagation_hosts not set Framework transactions are sent only once a rate is set.
profiles_sample_rate off
release_health not set "process" or "request" sessions.
before_send, before_breadcrumb, max_breadcrumbs none, none, 100
sample_rate, ignore_errors, deny_urls, allow_urls, ignore_transactions 1.0, empty
enabled, debug, on_error True, False, none debug prints to stderr.

Without init, the plain client sends during the call and raises ApphelmError (with status and code) when AppHelm refuses. Flag checks never raise; they return False.

Go (apphelm.Config, Go 1.21+)

Field Default What it does
APIKey, WorkspaceID, ProductID required
BaseURL, Timeout https://apphelm.dev, 10 s
Release, Environment not set
FlushAt, FlushInterval, MaxQueueSize 20, 5 s, 10000
MaxRetries, RetryBackoff, FlushConcurrency 3, 0.5 s doubling to 10 s, 4 Network errors, 408, 429 and 5xx are retried.
SyncMode false Send during the call and return the delivery error: for scripts, tests and serverless.
LocalEvaluation, FlagsPollInterval, FlagsMaxStale false, 10 s, 60 s Needs products:read.
TracesSampleRate, TracesSampler, TracePropagationHosts not set Middleware transactions are sent only once set.
ProfilesSampleRate off
SessionMode off SessionModeProcess or SessionModeRequest. Needs Release.
BeforeSend, BeforeBreadcrumb, MaxBreadcrumbs, OnError none, none, 100, discard
SampleRate, IgnoreErrors, DenyURLs, AllowURLs, IgnoreTransactions (and …Regexp) all, empty
Enabled, Debug, DebugWriter enabled, false, os.Stderr

Ruby (Apphelm::Client.new(…) or Apphelm.init(…), Ruby 3.1+)

Option Default What it does
api_key:, workspace_id:, product_id: required
base_url:, timeout: https://apphelm.dev, 10
release:, environment: not set
flush_at:, flush_interval:, max_queue_size: 20, 5, 10_000 Sent from a background thread; restarted after fork.
max_retries:, flush_concurrency:, sync_mode: 3, 4, false
local_evaluation:, flags_poll_interval:, flags_max_stale: false, 10, 60
traces_sample_rate:, traces_sampler:, trace_propagation_hosts: not set
profiles_sample_rate:, release_health: off :process or :request.
before_send:, before_breadcrumb:, max_breadcrumbs:, on_error: none, none, 100, none
sample_rate:, ignore_errors:, deny_urls:, allow_urls:, ignore_transactions: 1.0, empty
enabled:, debug: true, false debug prints [apphelm] … to $stderr.

PHP (new Apphelm\Client(…), PHP 8.1+)

Option Default What it does
apiKey, workspaceId, productId required
baseUrl, timeout https://apphelm.dev, 5.0 s
release, environment not set
batch, flushAt, maxQueueSize false, 20, 1000 By default each event is sent during the call. batch: true queues in memory and sends at shutdown.
maxRetries 2 Network errors, 408, 429 and 5xx.
localEvaluation, flagsRefreshInterval, flagsMaxStale, cache false, 10.0, 60.0, none A PSR-16 cache shares configs between requests.
tracesSampleRate, tracesSampler, tracePropagationHosts, profilesSampleRate not set
sessionMode not set
beforeSend, beforeBreadcrumb, maxBreadcrumbs, onError none, none, 100, none
sampleRate, ignoreErrors, denyUrls, allowUrls, ignoreTransactions 1.0, empty
enabled, debug, debugOutput true, false, error_log

Call $apphelm->registerErrorHandlers() to report uncaught exceptions and fatal errors. The Laravel and Symfony integrations do this for you.

.NET (ApphelmOptions, .NET 8 or .NET Standard 2.0)

Option Default What it does
ApiKey, WorkspaceId, ProductId required
BaseUrl, Timeout https://apphelm.dev, 10 s
Release, Environment not set
FlushAt, FlushInterval, MaxQueueSize, MaxRetries 20, 10 s, 10000, 3
ShutdownTimeout 10 s How long disposing waits for the queue.
TracesSampleRate, TracesSampler, TracePropagationHosts not set
SessionMode off
BeforeSend, OnError none
SampleRate, IgnoreErrors, IgnoreErrorPatterns, DenyUrls, AllowUrls, IgnoreTransactions 1, empty
Enabled, Debug, DiagnosticLogger true, false, stderr

Uncaught exceptions in a console app or worker are reported after apphelm.CaptureUnhandledExceptions(). In ASP.NET Core, UseApphelm() reports exceptions that escape the pipeline.

Rust (Options::new(key)…, Rust 1.82+)

Option Default What it does
workspace_id, product_id none Required to capture; product_id also for flags.
base_url, timeout https://apphelm.dev, 10 s
release, environment none
flush_at, flush_interval, max_queue_size 20, 10 s, 10000
max_retries, retry_delay, shutdown_timeout 3, 500 ms, 10 s
local_evaluation, poll_interval, max_stale off, 10 s, 60 s
traces_sample_rate, traces_sampler, trace_propagation_hosts not set
profiles_sample_rate off Needs the profiling feature.
release_health SessionMode::Off
before_send, before_breadcrumb, max_breadcrumbs, on_error none, none, 100, none
sample_rate, enabled, debug 1, true, false debug prints [apphelm] … to stderr.

Cargo features: async (tokio AsyncClient), tower and axum (ApphelmLayer), log, tracing, profiling, http. Panics are reported after apphelm.install_panic_hook().

Elixir (config :apphelm, …, Elixir 1.14+)

Option Default What it does
:api_key, :workspace_id, :product_id required With :api_key set, the :apphelm application starts the client itself.
:base_url "https://apphelm.dev"
:release, :environment nil
:flush_at, :flush_interval, :shutdown_timeout 20, 10 s, 5 s
:traces_sample_rate, :traces_sampler not set Apphelm.Plug, Phoenix and Oban transactions are sent only once set.
:profiles_sample_rate, :session_mode off, nil
:sample_rate, :enabled, :debug 1.0, true, false debug logs through Logger at :info.
:logs_min_level :info

See Apphelm.Config for the full list (:max_retries, :timeout, :before_send, :on_error, local evaluation).

HTTP

There are no client options. Send environment and release as event properties where the event type takes them, and an Idempotency-Key header on writes that need one. See Using the API.

#A production configuration

A typical production setup sets the environment and release, samples traces, and turns off sending in tests.

No example for this step; showing Next.js.

app/apphelm-provider.tsx
<ApphelmProvider options={{
  key: process.env.NEXT_PUBLIC_APPHELM_KEY!, workspaceId: "org_…", productId: "prd_…",
  environment: process.env.NEXT_PUBLIC_VERCEL_ENV ?? "production",
  release: process.env.NEXT_PUBLIC_APP_VERSION,
  tracesSampleRate: 0.2,
  replay: { sampleRate: 0.1, onErrorSampleRate: 1 },
}}>
<ApphelmProvider options={{
  key: import.meta.env.VITE_APPHELM_KEY, workspaceId: "org_…", productId: "prd_…",
  environment: import.meta.env.MODE, release: import.meta.env.VITE_APP_VERSION,
  tracesSampleRate: 0.2, replay: { sampleRate: 0.1, onErrorSampleRate: 1 },
}}>
export const apphelm = createBrowserSdk({
  key: import.meta.env.VITE_APPHELM_KEY, workspaceId: "org_…", productId: "prd_…",
  environment: import.meta.env.MODE, release: import.meta.env.VITE_APP_VERSION,
  tracesSampleRate: 0.2, replay: { sampleRate: 0.1, onErrorSampleRate: 1 },
});
export const apphelm = createBrowserSdk({
  key: PUBLIC_APPHELM_KEY, workspaceId: "org_…", productId: "prd_…",
  environment: import.meta.env.MODE, release: import.meta.env.VITE_APP_VERSION,
  tracesSampleRate: 0.2, replay: { sampleRate: 0.1, onErrorSampleRate: 1 },
});
window.apphelm = createBrowserSdk({
  key: "ahl_pub_…", workspaceId: "org_…", productId: "prd_…",
  environment: "production", release: "site@2026.11.07",
  tracesSampleRate: 0.2, replay: { sampleRate: 0.1, onErrorSampleRate: 1 },
});
export const apphelm = new Apphelm({
  apiKey: process.env.APPHELM_API_KEY!, workspaceId: "org_…", productId: "prd_…",
  environment: process.env.NODE_ENV, release: process.env.GIT_SHA,
  tracesSampleRate: 0.2, enabled: process.env.NODE_ENV !== "test",
});
apphelm.captureUnhandled(); // report uncaught exceptions and unhandled rejections
export const apphelm = createReactNativeSdk({
  apiKey: process.env.EXPO_PUBLIC_APPHELM_KEY!, workspaceId: "org_…", productId: "prd_…",
  storage: AsyncStorage, appState: AppState,
  release: "shop@2.4.0+240", environment: __DEV__ ? "development" : "production",
  tracesSampleRate: 0.2,
});
let options = ApphelmOptions(apiKey: key, workspaceId: "org_…", productId: "prd_…",
                             release: "shop@2.4.0+240", environment: "production", tracesSampleRate: 0.2)
let apphelm = ApphelmClient(options: options)
try? apphelm.installCrashReporting()
Task { await apphelm.sendPendingCrashReports() }
Apphelm.setup(this, ApphelmConfig(BuildConfig.APPHELM_API_KEY, "org_…", "prd_…").apply {
    environment = if (BuildConfig.DEBUG) "debug" else "production"
    tracesSampleRate = 0.2
    enabled = !BuildConfig.DEBUG
})
void main() => Apphelm.init(
      ApphelmConfig(
        apiKey: const String.fromEnvironment('APPHELM_KEY'), workspaceId: 'org_…', productId: 'prd_…',
        release: 'shop@2.4.0+240', environment: kReleaseMode ? 'production' : 'development',
        tracesSampleRate: 0.2,
      ),
      appRunner: () => runApp(const MyApp()), // also reports uncaught Flutter errors
    );
val apphelm = ApphelmClient(ApphelmOptions(
    apiKey = System.getenv("APPHELM_API_KEY"), workspaceId = "org_…", productId = "prd_…",
    release = System.getenv("GIT_SHA"), environment = "production", tracesSampleRate = 0.2,
))
Runtime.getRuntime().addShutdownHook(Thread { apphelm.close() })
apphelm.init(
    api_key=os.environ["APPHELM_API_KEY"], workspace_id="org_…", product_id="prd_…",
    release=os.environ.get("GIT_SHA"), environment="production",
    traces_sample_rate=0.2, enabled=os.environ.get("APP_ENV") != "test",
)
client, err := apphelm.New(apphelm.Config{
	APIKey: os.Getenv("APPHELM_API_KEY"), WorkspaceID: "org_…", ProductID: "prd_…",
	Release: os.Getenv("GIT_SHA"), Environment: "production",
	TracesSampleRate: apphelm.Float(0.2),
})
if err != nil {
	log.Fatal(err)
}
defer client.Close()
Apphelm.init(api_key: ENV.fetch("APPHELM_API_KEY"), workspace_id: "org_…", product_id: "prd_…",
             release: ENV["GIT_SHA"], environment: Rails.env, traces_sample_rate: 0.2,
             enabled: !Rails.env.test?)
at_exit { Apphelm.shutdown }
$apphelm = new Client(
    apiKey: getenv('APPHELM_API_KEY'), workspaceId: 'org_…', productId: 'prd_…',
    release: getenv('GIT_SHA') ?: null, environment: 'production',
    tracesSampleRate: 0.2, enabled: getenv('APP_ENV') !== 'testing',
);
$apphelm->registerErrorHandlers();
await using var apphelm = new ApphelmClient(new ApphelmOptions
{
    ApiKey = Environment.GetEnvironmentVariable("APPHELM_API_KEY")!,
    WorkspaceId = "org_…", ProductId = "prd_…",
    Release = "api@1.2.3", Environment = "production", TracesSampleRate = 0.2,
});
using var unhandled = apphelm.CaptureUnhandledExceptions();
let apphelm = Client::new(
    Options::new(std::env::var("APPHELM_API_KEY")?)
        .workspace_id("org_…").product_id("prd_…")
        .release("api@1.4.0").environment("production")
        .traces_sample_rate(0.2),
)?;
apphelm.install_panic_hook();
config :apphelm,
  api_key: System.fetch_env!("APPHELM_API_KEY"),
  workspace_id: "org_…",
  product_id: "prd_…",
  release: System.get_env("RELEASE"),
  environment: "production",
  traces_sample_rate: 0.2

In the browser, nothing is recorded or sent until analytics consent is given, and nothing is stored on the device before it either. Session replay needs its own replay consent on top. If the browser sends Global Privacy Control, consent cannot be given and nothing is sent. Feature flags still load and read without consent.

Mobile SDKs record by default and offer an opt-out that is remembered across launches; replay always waits for replay consent. Server SDKs send what you send them. Privacy, consent and data controls covers purposes, masking and deletion.

No example for this step; showing Next.js.

const apphelm = useApphelm();
// From your consent banner:
apphelm?.setConsent({ analytics: true, replay: true });
// Withdrawn: queued events are dropped and autocapture, errors and replay stop.
apphelm?.setConsent({ analytics: false, replay: false });
const apphelm = useApphelm();
apphelm?.setConsent({ analytics: true, replay: true }); // from your consent banner
const apphelm = useApphelm();
apphelm?.setConsent({ analytics: true, replay: true }); // from your consent banner
apphelm.client.setConsent({ analytics: true, replay: true }); // from your consent banner
window.apphelm.setConsent({ analytics: true, replay: true }); // from your consent banner
window.apphelm.getConsent(); // { analytics, replay, ads }
apphelm.optOut();              // drops the queue and sends nothing until optIn(); remembered
apphelm.optIn();
apphelm.setReplayConsent(true); // replay records nothing before this
apphelm.optOut()               // remembered across launches
apphelm.optIn()
apphelm.setReplayConsent(true)
Apphelm.optOut()               // nothing is queued or sent; remembered
Apphelm.optIn()
Apphelm.setReplayConsent(true)
Apphelm.instance.optOut();
Apphelm.instance.optIn();
Apphelm.instance.setReplayConsent(true);
apphelm.optOut() // per client; a JVM server usually decides per event instead

If you already know the visitor's choice at start-up (a stored consent cookie), pass it as consent in the options so the first page view is recorded. Pass consent: { analytics: true, replay: false, ads: "measurement" } to also capture the landing page's ad click ids.

#Flush and shut down

Browser SDKs send on their own and once more when the page is hidden. Mobile SDKs send on a timer, when enough events wait and when the app goes to the background. Servers need you to send what is queued before the process exits, or the last events are lost.

No example for this step; showing JavaScript (browser).

await window.apphelm.flush();  // events, replay chunks and log lines now
window.apphelm.destroy();      // stop everything and drop the queue (single-page app teardown, tests)
await apphelm.flush(2000); // wait at most 2 s for sends in flight; true when all finished
await apphelm.close(2000); // flush, then send nothing more. Call it before a script or serverless function ends.
await apphelm.flush();
await apphelm.shutdown(); // send what is queued, stop the timer and the AppState listener
let sent = await apphelm.flush(timeout: 2) // false on timeout
await apphelm.close(timeout: 2)            // flush, then send nothing more
Apphelm.flush()            // in the background
Apphelm.flush(2_000)       // blocking, true when everything was sent
Apphelm.close(2_000)
final sent = await Apphelm.instance.flush(timeout: const Duration(seconds: 2));
await Apphelm.close(timeout: const Duration(seconds: 2));
apphelm.flush()  // blocking
apphelm.close()  // stops the timer and sends what is queued
apphelm.flush(timeout=2.0)  # True when everything was sent in time
apphelm.close(timeout=2.0)  # flush, then stop sending; init registers an atexit flush for you
client.FlushTimeout(2 * time.Second) // true when everything was sent
client.Close()                       // after your HTTP server has stopped taking requests
APPHELM.flush(2)   # wait at most 2 s
APPHELM.shutdown   # in at_exit; in Puma cluster mode also in on_worker_shutdown
$apphelm->flush(2.0);  // after each job in a queue worker, or each request in Octane, RoadRunner or Swoole
$apphelm->close(2.0);
await apphelm.FlushAsync(TimeSpan.FromSeconds(2));
await apphelm.DisposeAsync(); // `await using` and AddApphelm do this for you
apphelm.flush_timeout(Duration::from_secs(2));
apphelm.shutdown(); // also runs when the last clone is dropped; on AsyncClient, .await it
Apphelm.flush(2_000) # in a script or Mix task; the application flushes on stop
Apphelm.close(2_000)

#Offline, queues and retries

Platform Where events wait What happens when a send fails
Browser Memory, up to 100 events or 48,000 bytes With no network, or a 408, 429 or 5xx answer, the batch goes back on the queue and is tried on the next flush, every 5 seconds. Any other refusal (a revoked key, a wrong origin, an invalid batch) is dropped. Lost when the tab closes.
Node.js Nothing is queued The call rejects with ApphelmError.
React Native storage (AsyncStorage), up to 1,000 With no network, or a 408, 429 or 5xx answer, kept and retried later, across launches. Any other refusal (a revoked key, an invalid or too large event): dropped.
iOS, Android, Flutter On the device, up to 1,000 With no network, or a 408, 429 or 5xx answer, the event and those after it stay queued, in order, with the same ids. Any other refusal is dropped.
JVM Memory (or storageDirectory), up to 100 As on Android.
Python Background queue of 1,000 with init Passed to on_error; the plain client raises.
Go, Ruby, .NET, Rust, Elixir Memory, up to 10,000 Network errors, 408, 429 and 5xx retried with backoff (3 times); any other refusal is dropped and reported to OnError/on_error.
PHP Sent during the call, or memory with batch: true Retried twice, then returns false. Never throws.

Every SDK gives each event its id when it is created, so a retried event is stored and billed once.

#Framework notes

Next.js App Router. The install step above puts ApphelmProvider in a client component and wraps the root layout. For flags that are right on the first render, with no flicker, use the App Router helpers:

// middleware.ts: one anonymous id cookie (apphelm_id) shared by server and browser
import { NextResponse, type NextRequest } from "next/server";
import { apphelmMiddleware } from "@sansavision/apphelm/next/server";
export function middleware(request: NextRequest) { return apphelmMiddleware(request, NextResponse); }

// app/layout.tsx (server component)
import { cookies } from "next/headers";
import { getBootstrap } from "@sansavision/apphelm/next/server";
import { ApphelmNextProvider } from "@sansavision/apphelm/next";
import { apphelm } from "@/lib/apphelm"; // the server client from the install step

export default async function RootLayout({ children }: { children: React.ReactNode }) {
  const bootstrap = await getBootstrap({ apphelm, cookies: await cookies() });
  return <html lang="en"><body>
    <ApphelmNextProvider options={{ key: process.env.NEXT_PUBLIC_APPHELM_KEY!, workspaceId: "org_…", productId: "prd_…" }} bootstrap={bootstrap}>{children}</ApphelmNextProvider>
  </body></html>;
}

On the server side, instrumentation.ts can report errors from server components, route handlers, server actions and middleware, and trace requests:

// instrumentation.ts
import { registerApphelm, apphelmOnRequestError } from "@sansavision/apphelm/server";
import { apphelm } from "@/lib/apphelm";
export function register() { registerApphelm(apphelm); }
export const onRequestError = apphelmOnRequestError(apphelm);

Wrap a route handler with withApphelm(handler, { client: apphelm, name: "GET /api/orders/[id]" }) and a server action with withServerActionInstrumentation("placeOrder", { client: apphelm, headers: await headers() }, …). redirect() and notFound() are never reported. For source maps, wrap your config with withApphelmConfig from @sansavision/apphelm/next/config; see Source maps and debug symbols.

React. ApphelmProvider creates one client; read it with useApphelm(), and use useFeatureFlag, useTrack, ApphelmErrorBoundary and withErrorBoundary from @sansavision/apphelm/react (React 19 or later). With Create React App, read the key from process.env.REACT_APP_APPHELM_KEY. For router-named transactions, see @sansavision/apphelm/tracing/react-router in Tracing and performance.

Vue 3. Instead of a module, you can install the plugin, which also reports errors Vue catches and gives you composables:

import { apphelm } from "@sansavision/apphelm/vue";
app.use(apphelm, { options: { key: import.meta.env.VITE_APPHELM_KEY, workspaceId: "org_…", productId: "prd_…" }, router });
// In setup(): const newCheckout = useFeatureFlag("new-checkout"); // ComputedRef<boolean>

Nuxt 3. Two plugins: a server one that evaluates flags for the first render, and a universal one that starts the browser client and provides useNuxtApp().$apphelm.

// plugins/01.apphelm.server.ts
import { apphelmNuxtServer } from "@sansavision/apphelm/nuxt";
import { Apphelm } from "@sansavision/apphelm";
const serverClient = new Apphelm({ apiKey: process.env.APPHELM_API_KEY!, workspaceId: "org_…", productId: "prd_…" });
export default defineNuxtPlugin(apphelmNuxtServer({ apphelm: serverClient }));

// plugins/02.apphelm.ts
import { apphelmNuxtPlugin } from "@sansavision/apphelm/nuxt";
export default defineNuxtPlugin((nuxtApp) =>
  apphelmNuxtPlugin({ options: { key: useRuntimeConfig().public.apphelmKey, workspaceId: "org_…", productId: "prd_…" } })(nuxtApp));

SvelteKit. Create the client in the root layout, in the browser only, and let the server hook evaluate flags for the first render:

// src/hooks.server.ts
import { apphelmHandle, handleErrorWithApphelm } from "@sansavision/apphelm/svelte";
import { apphelm } from "$lib/server/apphelm"; // new Apphelm({ apiKey: env.APPHELM_API_KEY, … })
export const handle = apphelmHandle({ apphelm, trace: apphelm });
export const handleError = handleErrorWithApphelm(apphelm);

// src/routes/+layout.server.ts
export const load = async ({ locals }) => ({ apphelm: await locals.apphelm.bootstrap() });
<!-- src/routes/+layout.svelte -->
<script>
  import { afterNavigate } from "$app/navigation";
  import { PUBLIC_APPHELM_KEY } from "$env/static/public";
  import { createApphelm, trackPageviews } from "@sansavision/apphelm/svelte";
  export let data;
  const apphelm = createApphelm({ options: { key: PUBLIC_APPHELM_KEY, workspaceId: "org_…", productId: "prd_…" }, bootstrap: data.apphelm });
  trackPageviews(afterNavigate, apphelm);
  const newCheckout = apphelm.featureFlag("new-checkout"); // $newCheckout in markup
</script>

Create the client per layout, not at module level: on the server a module-level client would be shared by every request.

Angular (16 or later) uses the browser SDK through @sansavision/apphelm/angular. provideApphelm registers ApphelmService (flags as signals), an ErrorHandler that reports errors, and router page views:

import { provideApphelm } from "@sansavision/apphelm/angular";
import { Router } from "@angular/router";
bootstrapApplication(AppComponent, { providers: [
  provideApphelm({ options: { key: environment.apphelmKey, workspaceId: "org_…", productId: "prd_…" }, router: Router }),
] });
// In a component: inject(ApphelmService).featureFlag("new-checkout")

Plain HTML. The script tag in the install step loads the latest version from jsDelivr. Pin a version in the URL (@sansavision/apphelm@0.8.1/dist/browser.js) so a release never changes your site without you.

Express: app.use(expressRequestHandler(apphelm)) first, and setupExpressErrorHandler(app, apphelm) after your routes. Fastify: await fastify.register(fastifyIntegration(apphelm)). Both report errors without a 4xx status and name transactions by route. instrument(apphelm, { integrations: [httpServerIntegration(), …] }) adds automatic HTTP, fetch and database spans. All of these are exported from @sansavision/apphelm/server. Next.js server code is under Next.js in the language menu.

Expo. Keys in EXPO_PUBLIC_ variables are inlined into the bundle, which is why this key must be events:write only. Read the version with expo-application: appInfo: () => ({ version: Application.nativeApplicationVersion, build: Application.nativeBuildVersion }).

Screens. With React Navigation (and Expo Router, which is built on it), pass the tracker to the container so each focused route is a $screen:

const onChange = apphelm.navigationTracker();
<NavigationContainer ref={ref} onReady={() => onChange(ref.getRootState())} onStateChange={onChange}>

Replay and Hermes profiling need native modules (@sansavision/apphelm-react-native-replay, @sansavision/apphelm-react-native-profiler) and a rebuild of the app; a JavaScript reload is not enough.

SwiftUI views are not captured on their own: add .apphelmScreen("Checkout") to each screen's root view, and .apphelmTrace("Checkout") for a screen-load transaction. UIKit view controllers send a $screen automatically (captureScreenViews); with tracing on and enableUIViewControllerTracing, each also gets a screen-load transaction. Create one ApphelmClient at launch (in your App initialiser or application(_:didFinishLaunchingWithOptions:)) and keep it.

Jetpack Compose and Navigation. Add com.sansavision:apphelm-android-compose for rememberNavController().withApphelmObservableEffect() (each destination is a screen) and Modifier.apphelmTag("pay_button") (named tap breadcrumbs). With Fragments and AndroidX Navigation, add navController.addOnDestinationChangedListener(ApphelmNavigationListener()). Call Apphelm.setup in your Application.onCreate and register the class in AndroidManifest.xml with android:name.

Add ApphelmObserver() to navigatorObservers for screen views. apphelm_flutter_native adds native crashes, ANRs and app hangs; apphelm_sqflite, apphelm_drift and apphelm_file add database and file spans. All come from the same pub repository as apphelm_flutter, at the same version.

Django: call apphelm.init(…) in settings.py and put "apphelm_django.ApphelmMiddleware" first in MIDDLEWARE. Flask: apphelm_flask.init_app(app). FastAPI and Starlette: app.add_middleware(ApphelmMiddleware) from apphelm_asgi. Celery: apphelm_celery.instrument() in the web app and the worker. requests and httpx: apphelm_http.instrument(). SQLAlchemy: apphelm_sqlalchemy.instrument(). Each reports unhandled exceptions with handled: False; transactions are sent once you set traces_sample_rate. The signed-in user's id is sent as a hash only (capture_user=False turns it off).

client.Middleware(mux) works with any router that takes an http.Handler (http.ServeMux, chi, gorilla/mux): a request scope, an http.server transaction and panic reporting. For Gin or Echo, recover in their middleware and call client.CaptureExceptionContext(ctx, err, apphelm.ExceptionOptions{}). In goroutines, defer client.Recover(). client.Transport(base) adds spans and traceparent to outgoing requests; client.SlogHandler connects log/slog.

Rails: call Apphelm.init(…) in config/initializers/apphelm.rb; the Railtie adds the Rack middleware, Active Record and view spans, Active Job transactions and the Rails error reporter subscriber. Sidekiq: Apphelm::Sidekiq.install!. Rack and Sinatra: use Apphelm::Rack, client: APPHELM. In Puma cluster mode, add on_worker_shutdown { APPHELM.shutdown } to config/puma.rb.

Laravel (10 to 12): add Apphelm\Laravel\ApphelmServiceProvider::class to bootstrap/providers.php (it is not auto-discovered) and set APPHELM_API_KEY, APPHELM_WORKSPACE_ID, APPHELM_PRODUCT_ID and, optionally, APPHELM_RELEASE, APPHELM_ENVIRONMENT (default APP_ENV) and APPHELM_TRACES_SAMPLE_RATE. It reports exceptions, traces requests and flushes after each request and command; without APPHELM_API_KEY it sends nothing. In queue workers: Queue::after(fn () => app(\Apphelm\Client::class)->flush());. Symfony (6.4, 7): register Apphelm\Symfony\ApphelmBundle and configure config/packages/apphelm.yaml. Under PHP-FPM, fastcgi_finish_request() lets the visitor have the response before a batch is sent.

ASP.NET Core: add SansaVision.Apphelm.AspNetCore and register the client from configuration; it is flushed when the host stops.

builder.Services.AddApphelm(builder.Configuration.GetSection("Apphelm"), options => options.TracesSampleRate = 0.2);
builder.Logging.AddApphelm(); // warnings become breadcrumbs
var app = builder.Build();
app.UseApphelm();             // request scope, transactions, unhandled exceptions

Put the key in user secrets or the Apphelm__ApiKey environment variable, not in appsettings.json.

Axum, hyper, tonic: enable the axum (or tower) feature and add .layer(apphelm::ApphelmLayer::new(&apphelm)) after your routes; call apphelm.install_panic_hook() and apphelm.shutdown().await after axum::serve returns. Actix Web: share an AsyncClient with web::Data and shut it down when HttpServer::run returns.

Phoenix and Plug: add use Apphelm.Plug to your endpoint (in a Plug.Router, before use Plug.ErrorHandler). Add :logger.add_handler(:apphelm, Apphelm.LoggerHandler, %{config: %{name: Apphelm}}) in application.ex for crashes in processes, and Apphelm.Telemetry.attach(ecto: [[:my_app, :repo]], phoenix: true, oban: [cron: true], finch: true) for Ecto, Phoenix, Oban and Finch spans. Add the AppHelm Hex repository in CI too, before mix deps.get.

#Troubleshooting

Symptom Likely cause What to do
Nothing arrives from the browser No analytics consent yet, or the page's origin is not the key's Call setConsent({ analytics: true }); check the origin with debug: true (a 401 means the key or origin is wrong)
Nothing arrives in automated browser tests Headless browsers are filtered as bots (202, bot_filtered) Test against your own mock, or check events from a normal browser
A server event is refused with 403 scope_denied The key lacks events:write Create a key with events:write in Settings → API keys
The last events of a script or job never arrive The process exited before the queue was sent Call flush/close/shutdown before exit (see Flush and shut down)
No transactions on the Performance page No trace sample rate is set Set tracesSampleRate (or your SDK's equivalent)

Troubleshooting covers every status code and platform in detail.