# Browser SDK

`@visibling/sdk/browser` is the zero-dependency browser client. It captures pageviews, custom events, identify calls, and uncaught errors, and ships its batches through your own origin so ad-blockers never strip them. The gzipped bundle stays under 4 KB.

```sh
pnpm add @visibling/sdk
```

## Create a client

```ts
import { createVisiblingClient } from "@visibling/sdk/browser";

export const visibling = createVisiblingClient({
  endpoint: "/_v",
  release: "2026.12.1",
  environment: "production",
});
```

Create one client per page and import it from your root route. Creating a second client adds a second set of listeners and double-counts pageviews.

### Configuration

| Option | Type | Default | Purpose |
| --- | --- | --- | --- |
| `endpoint` | `string` | required | First-party proxy base path. Without `publicKey`, batches post to `<endpoint>/e`; `"/_v"` becomes `/_v/e`. |
| `publicKey` | `string` | unset | Direct browser ingest. Set `endpoint` to the full Visibling ingest URL and this to a `vis_pub_` key. |
| `release` | `string` | unset | Release label attached to every event and error, capped at 128 characters. |
| `environment` | `string` | unset | Environment label, capped at 64 characters. Use exactly `internal` (lowercase) to mark internal/test traffic: product analytics excludes it by default. |
| `disabled` | `boolean` | `false` | Builds an inert client: no listeners, no storage, no network. |
| `respectDnt` | `boolean` | `false` | When `true`, builds an inert client if the browser reports Do Not Track (`navigator.doNotTrack === "1"` or `"yes"`): no listeners, no storage, no network. |
| `autoPageviews` | `boolean` | `true` | Capture the initial pageview plus `pushState` / `replaceState` / `popstate` navigations. |
| `captureUnhandledErrors` | `boolean` | `true` | Capture `window.error` and `unhandledrejection` events. |
| `sessionTimeoutMs` | `number` | `1800000` | Sliding idle window before the session id rotates (30 minutes). |
| `maxBatchSize` | `number` | `20` | Items per batch before an immediate flush, clamped to 1–100. |
| `flushIntervalMs` | `number` | `2000` | Automatic flush interval. |
| `maxIdenticalErrorsPerMinute` | `number` | `10` | Per-tab storm throttle for identical error type and message. |

## Methods

### `track(name, props?)`

Capture a custom product event. The name is capped at 128 characters; props are snapshotted at capture time, so later mutation cannot rewrite a queued event.

```ts
visibling.track("checkout_started", { plan: "starter", items: 3 });
```

### `pageview(path?)`

Capture a pageview. Defaults to the current `location.pathname`; query strings and fragments are dropped so tokens never leave the page. With `autoPageviews` on, the client already calls this for the first page and every History navigation.

```ts
visibling.pageview("/pricing");
```

### `identify(distinctId, traits?)`

Link the anonymous session to a known user. This is meaningful only in direct `vis_pub_` mode. Through the first-party proxy the server owns identity and the proxy discards browser-supplied user fields, so use `getIdentity` in `createVisiblingProxy` instead.

```ts
visibling.identify("user_123", { email: "maya@example.com", plan: "starter" });
```

### `captureException(error, extra?)`

Capture an error with the current breadcrumb trail. The message is capped at 2048 characters and the stack at 16 KB. Extra properties become the occurrence's context.

```ts
try {
  await saveOrder(order);
} catch (error) {
  visibling.captureException(error, { orderId: order.id });
  throw error;
}
```

### `addBreadcrumb(category, message, data?)`

Add one entry to the 20-item ring buffer that travels with the next captured error.

```ts
visibling.addBreadcrumb("cart", "applied coupon", { code: "WELCOME10" });
```

### `flush()`

Send everything queued right now. The client also flushes when the page becomes hidden and on `pagehide`.

### `destroy()`

Flush, remove every listener, restore patched History methods, and stop the flush timer. `destroy()` is permanent: the client never captures again. Do not call it from a React effect cleanup, because React 19 StrictMode's development double-mount would leave analytics dead after the first cleanup.

## Direct browser mode

A `vis_pub_` key lets a browser post straight to Visibling without a proxy. Create it under **Project settings → Keys**, then point the client at the ingest URL:

```ts
const visibling = createVisiblingClient({
  endpoint: "https://visibling.com/api/v1/ingest",
  publicKey: "vis_pub_your_key_here",
  release: "2026.12.1",
});
```

Direct mode sends the key as `x-visibling-key` and uses `fetch(..., { keepalive: true })`; `sendBeacon` cannot attach headers. The key is public by design, but restrict where it can be used:

- Set **allowed origins** on the project. When the list is non-empty, ingest accepts a public key only when the request `Origin` matches an entry exactly.
- A `vis_pub_` key cannot set `plan` or `externalOrgId` on the end-user directory, and cannot label its errors as worker or Cloudflare issues. Those fields are server-enrichment only.

The first-party proxy remains the recommended path: it keeps even the public key out of the bundle and attaches trusted identity.

## What the client captures

- The initial pageview and every History navigation, with the path stripped of query strings and fragments.
- `document.referrer` reduced to a host name.
- A coarse device type derived from the user agent: `desktop`, `mobile`, `tablet`, or `bot`.
- Anonymous id and session id in `localStorage` (`vis_anon_id`, `vis_session`). A visitor with storage blocked still works for the lifetime of the page with in-memory ids.
- Uncaught errors and unhandled promise rejections, throttled to 10 identical errors per rolling minute per tab.
- Batches bounded to under 64 KB; an oversized event sheds its custom payload before it is dropped entirely.

Every post is best-effort. A failed request never surfaces to the host app.
