<!-- The SDK — Heystack docs. Rendered: https://heystack.dev/docs/sdk · Index: https://heystack.dev/llms.txt -->
# The SDK — `@heystack/otel`

`@heystack/otel` is runtime-aware telemetry that exports to Heystack. There's **one import per runtime**, so the root entry stays safe to load anywhere (including Edge and Workers) without dragging in the Node SDK.

```bash
npm install "@heystack/otel@>=0.19.1"
```

Always read your key from the environment — never paste it into source:

```bash
# .env
HEYSTACK_API_KEY=sk_live_…
```

The server key (`sk_live_…`) is for server-side code only. Browser code (`@heystack/otel/web`) uses a separate public, write-only **Browser key** (`hs_web_…`) in a `VITE_` / `NEXT_PUBLIC_` variable — **never put `sk_live_…` in client code**.

## Entry points

The package exposes five entries. Picking the wrong one is a production no-op — the Node SDK cannot run on Workers or Edge — so match the entry to where your code actually runs.

| Entry | Use it for | Main export |
| --- | --- | --- |
| `@heystack/otel` | Anywhere — pure helpers, no Node SDK loaded | `buildExporterConfig`, types |
| `@heystack/otel/node` | Long-running Node servers (Express, Fastify, NestJS) | `initHeystack` |
| `@heystack/otel/next` | Next.js — **any** deploy target | `registerHeystack` |
| `@heystack/otel/workers` | Standalone Cloudflare Workers | `instrument`, `flushHeystack`, `wrapExecutionContext`, `withSpan`, `withCloudflareSpan`, `addEvent`, `genAiRequestAttrs`, `genAiResponseAttrs`, named-class wrappers |
| `@heystack/otel/web` | Browser frontends (SPA / any client) — session replay + browser error collection | `instrumentWeb` |

The `/web` entry runs in the **browser** and is complementary to the server entries above (they trace the backend; `/web` records the browser). It captures **session replay** and **uncaught errors + `console.error`** as logs out of the box, can optionally emit browser distributed-tracing spans (`tracing: true`), and exposes **`reportBug`** for in-app bug reports. See **[Session Replay](https://heystack.dev/docs/replay)** for setup, the error-capture options (`errors`, `captureConsole`), and privacy/masking.

### In-app bug reports

`reportBug` lets a user file a bug from inside your app. It's headless (no widget — you build the button), and it auto-attaches the context a triager needs: the current URL, the replay session, the active trace, the release/commit, and the last few browser errors that happened before the report. Reports show up in the console under **Issues** (filter by bug reports), already linked to the session replay and trace.

```ts
import { instrumentWeb, reportBug } from "@heystack/otel/web";

await instrumentWeb({ apiKey: import.meta.env.VITE_HEYSTACK_WEB_KEY, service: "my-web-app" });

// Wire this to any UI you like:
await reportBug({
  message: "Checkout button does nothing",
  email: currentUser?.email,          // optional
  context: { plan: "pro", screen: "checkout" }, // optional metadata
});
```

Call `reportBug` any time after `instrumentWeb()`. A failed report never throws into your app.

## Runtime matrix

| Runtime | Import | Notes |
| --- | --- | --- |
| Next.js — any target (Vercel/Node **and** Cloudflare/OpenNext) | `@heystack/otel/next` | `registerHeystack` in `instrumentation.ts`. Auto-detects Node vs Cloudflare workerd and picks the right exporter. No-op on Edge. |
| Standalone Cloudflare Workers (`export default { fetch }`) | `@heystack/otel/workers` | Native-first `instrument()` wrapper. Cloudflare supplies supported platform coverage when `ctx.tracing` exists; direct export is the fallback. |
| Node / Express / Fastify / NestJS | `@heystack/otel/node` | `initHeystack`: auto-instrumentations + graceful shutdown. |
| Browser (SPA / any web frontend) | `@heystack/otel/web` | `instrumentWeb`: session replay + browser error/console collection; optional browser tracing. No-op on the server (SSR-safe). |
| Anywhere (pure helpers) | `@heystack/otel` | `buildExporterConfig`, types. No Node SDK loaded. |

## Attribute telemetry to a release/commit

Tag your telemetry with **which release and commit it came from** so Heystack can show **release health** and pinpoint the **suspect release / suspect commit** behind a regression. Two optional options do this on every runtime entry (`/node`, `/next`, `/workers`):

```ts
initHeystack({
  apiKey: process.env.HEYSTACK_API_KEY,
  service: "my-app",
  version: process.env.APP_VERSION, // a release identifier — "1.4.2", a git tag, etc.
  build: process.env.GIT_SHA,       // the commit SHA of this deploy
});
```

- **`version`** identifies the release (a semver, a git tag, or any string that changes per deploy). Heystack groups telemetry by it, so a spike in errors or latency can be attributed to the release that introduced it.
- **`build`** is the commit SHA. When you set a repository URL for the app in the console, Heystack turns the SHA into a deep link to the exact commit — so "suspect commit" jumps straight to the code.

Both are optional and only sent when set. Wire them from your build/deploy environment (e.g. `build: process.env.GIT_SHA` with `GIT_SHA=$(git rev-parse HEAD)` in CI). On Next.js pass them to `registerHeystack({ service, version, build })`; on Workers pass them in the `instrument()` config. On Node you can also skip the options and set `HEYSTACK_SERVICE_VERSION` (or `OTEL_SERVICE_VERSION`) and `HEYSTACK_SERVICE_BUILD` as environment variables instead.

## Privacy: URL redaction and client IP

The SDK removes secrets from URLs **before** they leave your app, on every entry (`/node`, `/next`, `/workers`, `/web`). Your app's real requests are unchanged — only what gets recorded is scrubbed:

- **Credentials in the address are dropped** — `https://user:pass@host/x` is recorded as `https://host/x`.
- **Sensitive query and fragment values become `REDACTED`** — e.g. a Gemini `?key=AIza…`, a Supabase `?apikey=…`, an OAuth `?code=…`, implicit-flow `#access_token=…&refresh_token=…`, and pre-signed S3/GCS signatures. Matching is case-insensitive. Built-in names: `key`, `api_key`, `apikey`, `api-key`, `token`, `access_token`, `refresh_token`, `id_token`, `auth_token`, `api_token`, `oauth_token`, `oauth_signature`, `code`, `sig`, `signature`, `password`, `passwd`, `pass`, `secret`, `client_secret`, `auth`, `authorization`, `session`, `sessionid`, `session_id`, `jwt`, `x-amz-signature`, `x-amz-credential`, `x-amz-security-token`, `x-goog-signature`, `x-goog-credential`. OAuth `state` is kept.
- Everything else — host, path, other parameters, plain `#anchors` — is recorded exactly as written.

It covers server request/outbound URLs (including Next.js and Node HTTP auto-instrumentation) and, in the browser, fetch traces, the page URL on errors, console logs, bug reports and session replay.

| Option | Default | Effect |
| --- | --- | --- |
| `redactQueryParams` | built-in list | Add parameter names (`["invite", "otp"]`), or `false` to turn parameter redaction off. Accepted by `initHeystack`, `registerHeystack`, `instrument` and `instrumentWeb`. |
| `captureClientIp` | `false` | Server entries. Record the end user's IP address (`client.address`). Off by default because an IP address is personal data in most jurisdictions — enable it only if you have a lawful basis and have told your users. |
| `captureGeo` | `"country"` | Workers only. `"country"` records the visitor's country; `"full"` adds region, city and network (ASN); `false` records none. |

To scrub URLs you log yourself with the same rules: `import { redactUrl } from "@heystack/otel"`.

> **Changed in 0.19.0:** redaction is on by default, the client IP is no longer recorded unless you set `captureClientIp: true`, and Workers record only the visitor's country unless you set `captureGeo: "full"`.

## Workers delivery, flushing, and latency

Native Workers mode has no SDK export to flush. In direct mode, the export is a `fetch()` POST and the isolate can be torn down after your handler returns. `instrument()` ends and serializes telemetry locally, starts the export, and hands its drain promise to `ctx.waitUntil`. It preserves handler `ctx.waitUntil(work)` calls and schedules their telemetry drains after `work` settles, so spans created after an `await` in background work are included. The response does not wait for the export network request or Heystack storage. Ending spans and serializing the payload still add a small amount of synchronous work, so the accurate claim is non-blocking network delivery, not zero latency.

- **Standalone Workers (`instrument()`)** — hands the drain to `ctx.waitUntil` automatically. No action needed.
- **Next on Cloudflare/OpenNext (`registerHeystack`)** — automatically borrows OpenNext's request `ctx.waitUntil` when `@opennextjs/cloudflare` is available. Other workerd frameworks must provide a handoff or explicit flush.
- **Node (`initHeystack`)** — flushes on `SIGTERM`/`SIGINT` automatically.

For advanced direct-mode code that calls `initHeystackWorkers()` instead of using `instrument()`, wrap the request context and route at least one `waitUntil` call through it. Constructing the wrapper alone does not schedule a drain:

```ts
import {
  initHeystackWorkers,
  wrapExecutionContext,
} from "@heystack/otel/workers";

export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext) {
    initHeystackWorkers({ apiKey: env.HEYSTACK_API_KEY, service: "my-worker" });
    const tracedCtx = wrapExecutionContext(ctx);
    try {
      return await handle(request, env, tracedCtx);
    } finally {
      tracedCtx.waitUntil(Promise.resolve());
    }
  },
};
```

If the context cannot be passed onward, import `flushHeystack` from `@heystack/otel/workers` and call `ctx.waitUntil(flushHeystack())` after ending your spans. The SDK emits one warning per isolate when a direct export settles without an `instrument()` drain, explicit/OpenNext handoff, or observed manual flush. There is no persistent buffer, so that warning means delivery can be lost at isolate teardown.

`wrapExecutionContext()` forwards optional and future context properties such as `cache`, `tracing`, and `props` to the original host object. Its generic return type preserves typed `ctx.props`. It registers the original background promise unchanged, then schedules its telemetry drain after that promise settles. The direct exporter makes one retry for network errors, `429`, and `5xx`. `Retry-After` seconds on a `429` are respected within a 2-second total retry-wait cap. Other `4xx` responses are not retried; after the retry fails, the payload is dropped. At most 512 exports run concurrently; excess exports fail before starting network work and increment `droppedPending`.

The `/workers` entry contains no `node:*` imports and remains safe to load on WinterCG runtimes without `nodejs_compat`. Native mode does not need that flag. Direct mode should enable it for cross-`await` context propagation; without it, export suppression and binding-parent fallback remain available, while outbound-fetch and manual span parenting after an `await` is best-effort.

For named Durable Object and Workflow class exports in direct mode, use `wrapDurableObjectClass()` and `wrapWorkflowEntrypointClass()`. The Durable Object helper covers fetch/alarm/prototype RPC and storage get/put/delete/list, but not transaction callback storage or instance arrow RPC methods. The Workflow helper covers `run`, callback-form `step.do(name, fn)`, and short wait markers. See the exact export examples and the native/direct coverage matrix in [Cloudflare Workers](https://heystack.dev/docs/cloudflare-workers).

## Verify it's working

- Pass `debug: true` to `initHeystack` to print diagnostic and export logs to the console.
- Run your app and make a request — traces appear in the [Heystack console](https://console.heystack.dev), usually within a minute.
- Confirm `HEYSTACK_API_KEY` is actually set in the running environment.
- Confirm the `service` name you set matches the app you're looking at in the console.

## Versioning and migration

> **Coming with 0.20.0.** The SDK will read one remote configuration document (`/v1/config`) so you can switch
> capture features, sampling and privacy settings from the console without redeploying, and an operator can switch off
> a misbehaving release. It will also upload source maps so browser errors show your original code. 0.19.x keeps
> working unchanged. See [the API reference](https://heystack.dev/docs/api#sdk-configuration).

- **`0.15.0`** combines native-tracing LLM `gen_ai.*` enrichment (including Mistral, configured AI gateways, streaming usage, and manual Workers AI helpers) with one bounded direct-export retry, `wrapExecutionContext`, named Durable Object and Workflow class wrappers, default-export email/generic Tail coverage, queue `ack()`/`retry()` detail, and expanded direct binding detection. It also upgrades the bundled OpenTelemetry SDK to the 2.x line; Node entries require Node ≥ 18.19 (or ≥ 20.6), while Workers and browser entries are unaffected. Native `ctx.tracing` remains authoritative for platform-owned coverage where available.
- **`0.10.0`** adds **release / commit attribution** — the optional `version` (release identifier → `service.version`) and `build` (commit SHA → `service.build`) options, on every runtime entry. They power release health and suspect release/commit in the console. See [Attribute telemetry to a release/commit](#attribute-telemetry-to-a-releasecommit).
- **Pin `@heystack/otel` `>=0.19.1`.** Older versions do not include the current Workers delivery and execution-model coverage.
- The pre-0.1.0 top-level default `initHeystack({ apiKey })` is **gone**. Use the subpath entries: `@heystack/otel/node`, `@heystack/otel/next`, `@heystack/otel/workers`. The root `@heystack/otel` entry now exposes only pure helpers (`buildExporterConfig`, types).
