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.
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.
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 onlyevents: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.
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:
npminstall @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).
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";exportconst 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:
npminstall @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).
Check: Load a page (or run the code) once, then press Check connection: the first event appears within a few seconds.
Vue / Nuxt
Install:
npminstall @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).
Check: Load a page (or run the code) once, then press Check connection: the first event appears within a few seconds.
Svelte / SvelteKit
Install:
npminstall @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).
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
<scripttype="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:
npminstall @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.
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.
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
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.
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_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.awaitusingvar 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.
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.
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.
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.pubfn 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:
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.
Load a page, open the app, or run a capture call on the server.
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.
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"
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.
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.
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.
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).
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.
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.
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.
Uncaught exceptions in a console app or worker are reported after apphelm.CaptureUnhandledExceptions(). In ASP.NET Core, UseApphelm() reports exceptions that escape the pipeline.
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.
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.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.
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 finishedawait 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 timeoutawait 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)
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.
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 browserimport{ NextResponse,type NextRequest }from"next/server";import{ apphelmMiddleware }from"@sansavision/apphelm/next/server";exportfunction 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 stepexportdefaultasyncfunction 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:
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:
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.
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:
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.
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.