# SDK API reference

> Every public function, component and type in the @belvador/* packages, by import path.

Every public export of the `@belvador/*` packages, version 0.6.1, grouped by import path. Anything not listed here — `@belvador/core`, the `/internal` subpaths and helper functions used between packages — is internal and can change without notice.

## Which functions each import path has

| Function | `browser` | `react` | `cloudflare` | `tanstack-start/client` | `tanstack-start/server` |
|---|---|---|---|---|---|
| `init` | ✓ | ✓ | — | ✓ | — |
| `withBelvador` | — | — | ✓ | — | ✓ |
| `captureException`, `captureMessage` | ✓ | ✓ | ✓ | ✓ | ✓ |
| `setUser`, `setTag`, `setTags`, `setContext` | ✓ | ✓ | ✓ | ✓ | ✓ |
| `addBreadcrumb`, `withScope`, `flush` | ✓ | ✓ | ✓ | ✓ | ✓ |
| `close`, `lastEventId` | ✓ | ✓ | ✓ | ✓ | — |
| `ErrorBoundary`, `withErrorBoundary`, `reactErrorHandler` | — | ✓ | — | ✓ | — |
| `withBelvadorRouter`, `belvadorOnCatch` | — | — | — | ✓ | — |
| `verifyIntegration` | ✓ | ✓ | ✓ | ✓ | ✓ |
| `captureResult` | ✓ | ✓ | ✓ | ✓ | ✓ |
| `privacyPolicy` | ✓ | ✓ | ✓ | ✓ | ✓ |
| `withMonitor`, `captureCheckIn`, `heartbeat` | — | — | ✓ | — | ✓ |
| `SDK_VERSION` | ✓ | ✓ | ✓ | ✓ | ✓ |

The root `@belvador/tanstack-start` export holds the middleware: `belvadorRequestMiddleware`, `belvadorFunctionMiddleware`, `withBelvadorRouter`, `belvadorOnCatch`, `isExpectedError` and `SDK_VERSION`.

## Starting the SDK

### `init(options): boolean`

From `@belvador/browser`, `@belvador/react` and `@belvador/tanstack-start/client`. Starts error tracking in the browser and returns whether it is running. It never throws: an invalid DSN logs one warning and leaves the SDK off. A second call with the same DSN does nothing; a different DSN does not replace the running client. Options: [SDK options](https://belvador.dev/en/docs/sdk/configuration).

### `withBelvador(options, handler): handler`

From `@belvador/cloudflare` and `@belvador/tanstack-start/server`. `options` is a function `(env) => WorkerOptions | undefined`, called with the Worker's environment. Returns a handler object of the same shape that reports errors from `fetch`, `scheduled`, `queue`, `email` and `tail`, re-throws them and leaves responses unchanged. Needs `nodejs_compat`.

### `privacyPolicy(json): BelvadorPrivacyPolicy | null`

Checks a policy copied from the project's Privacy page (**Copy as code**) and prepares it for `init({ privacyPolicy })`. Returns `null` and reports `BLV_PRIVACY_POLICY_INVALID` when it is not valid; never throws. See [Data protection](https://belvador.dev/en/docs/privacy). Since 0.6.0.

## Capturing

### `captureException(error, context?): string`

Reports an error. `context` can carry `tags`, `extra`, `contexts`, `level`, `user` or `fingerprint` for this event only. Returns an event ID, or `""` when the SDK is off.

```ts
captureException(error, { tags: { feature: "import" }, level: "warning" });
```

### `captureMessage(message, level?): string`

Reports a message without an exception, for example a state that should never happen. `level` is one of `fatal`, `error`, `warning`, `log`, `info`, `debug`.

### `captureResult(result, { operation, expected? }): result`

Reports the `error` of a `{ data, error }` result — Supabase, PostgREST or any client that returns errors instead of throwing — as one event typed by its database code, grouped by type and operation, and returns `result` unchanged. Never sends the SQL, `details` or `hint`. See [Database errors](https://belvador.dev/en/docs/sdk/database-errors). Since 0.6.0.

### `lastEventId(): string`

The ID of the last event this page sent, or `""`.

> [!NOTE]
> Event IDs are created inside your app. Getting one back does **not** prove the event reached your node — it can still be dropped by limits, the network or the edge. Check the project in Belvador.

## Context

| Function | Effect |
|---|---|
| `setUser({ id } \| null)` | Sets the current user. Only `id` is kept (up to 128 characters); emails, names and IPs are removed. `null` clears it. |
| `setTag(key, value)` | One searchable key/value on every following event. |
| `setTags({ … })` | Several tags at once. |
| `setContext(name, { … } \| null)` | A named block of structured data shown under **Contexts**. |
| `addBreadcrumb({ message, category, level, data })` | Records a step that happened before an error. Manual breadcrumbs work without turning on automatic ones. |

Everything you set passes through the same scrubbing as events. On Workers and TanStack Start servers, each request has its own scope, so context never leaks into another request.

### `withScope(callback)`

Runs `callback(scope)` with a temporary scope, for context that should apply to one capture only:

```ts
import { captureException, withScope } from "@belvador/browser";

withScope((scope) => {
  scope.setTag("job", "nightly-sync");
  scope.setFingerprint(["nightly-sync", "{{ default }}"]);
  captureException(error);
});
```

`scope` is the engine's scope object. When the SDK is off, the callback still runs, without a usable scope — do not rely on it there.

## Delivery

### `flush(timeoutMs = 2000): Promise<boolean>`

Waits until queued events are sent or the timeout passes. Resolves `true` when everything pending finished in time. Useful at the end of a script. On Workers you do not need it — `withBelvador` already waits in `waitUntil`.

### `close(timeoutMs = 2000): Promise<boolean>`

Flushes, then shuts the SDK down. Nothing is sent afterwards.

## React

### `ErrorBoundary`

A component that reports render errors from its children once, with the component stack, and renders `fallback` — an element or `({ error, componentStack, eventId, resetError }) => element`. Supports `onError`, `onReset`, `onMount`, `onUnmount` and `beforeCapture` like the Sentry React boundary. The user-feedback dialog props are not available.

### `withErrorBoundary(Component, props)`

Wraps a component in `ErrorBoundary` with the given props.

### `reactErrorHandler(callback?)`

Returns a handler for React 19's `onUncaughtError`, `onCaughtError` and `onRecoverableError` root options. The optional `callback(error, errorInfo, eventId)` runs after the report.

## TanStack Start

| Export | From | Use |
|---|---|---|
| `withBelvadorRouter(options)` | `@belvador/tanstack-start/client` (also root) | `createRouter(withBelvadorRouter({ routeTree, ... }))`: reports route errors, keeps your `defaultOnCatch`, adds TanStack's `ErrorComponent` when you set no `defaultErrorComponent` (0.5.0) |
| `belvadorOnCatch(error, errorInfo?)` | `@belvador/tanstack-start/client` (also root) | The reporter inside the helper; `createRouter({ defaultOnCatch: belvadorOnCatch })` works only where an error component exists |
| `belvadorRequestMiddleware` | `@belvador/tanstack-start` | Last entry of `requestMiddleware` in `createStart` |
| `belvadorFunctionMiddleware` | `@belvador/tanstack-start` | Last entry of `functionMiddleware` in `createStart` |
| `isExpectedError(error)` | `@belvador/tanstack-start` | `true` for redirects, `notFound()` and errors or responses with a status below 500 — the cases the middleware does not report |

## Monitors

Server packages only (`@belvador/cloudflare`, `@belvador/tanstack-start/server`), from 0.3.0. None of them throws. How to use them: [Add monitors with the SDK](https://belvador.dev/en/docs/monitors/setup).

### `withMonitor(slug, fn, options?): ReturnType<fn>`

Runs `fn(run)` as one monitored attempt and returns exactly what `fn` returns (or throws what it throws). `run.skip(reason)` marks the run Skipped, `run.unknown(reason)` marks it Outcome unknown; `run.checkInId` and `run.runId` are the ids sent. `options`: `schedule`, `timezone`, `checkinMargin`, `maxRuntime`, `failureIssueThreshold`, `recoveryThreshold` (create or update the monitor from code), `environment`, `runId`, `attempt`, `willRetry`.

### `captureCheckIn(checkIn, monitorConfig?): string`

Sends one check-in `{ monitorSlug, status: "in_progress" | "ok" | "error", checkInId?, duration?, environment?, runId?, attempt?, willRetry?, outcome?: "skipped" | "unknown", reason? }` and returns its id (`""` when the SDK is off or the slug is invalid).

### `heartbeat(slug, options?): void`

Sends one `ok` check-in, for every-N-minutes monitors. `options.environment` overrides the SDK's environment.

## Types

| Type | From |
|---|---|
| `BrowserOptions` | `@belvador/browser` |
| `ReactOptions`, `ErrorBoundaryProps`, `FallbackRender` | `@belvador/react` (`ReactOptions`, `ErrorBoundaryProps` also from `tanstack-start/client`) |
| `WorkerOptions`, `BelvadorEnv` | `@belvador/cloudflare`, `@belvador/tanstack-start/server` |
| `BelvadorEvent`, `BelvadorEventHint`, `BelvadorBreadcrumb`, `Scope`, `SeverityLevel` | `browser`, `react`, `cloudflare` |
