# Server SDK

`@visibling/sdk/server` sends the events a browser never sees: `signup_completed` with the auth method, `render_succeeded` or `render_failed` from a job, a device authorisation. It runs in Cloudflare Workers, Next.js (Node or Edge), Express, Bun and Deno, and talks to Visibling over HTTPS or an in-account Cloudflare Service Binding.

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

## Create a client

```ts
import { createVisiblingServer } from "@visibling/sdk/server";

export const visibling = createVisiblingServer({
  ingestKey: env.VISIBLING_SERVER_KEY, // vis_srv_...
  environment: "production",
  release: "2026.12.1",
});
```

Use a server key (`vis_srv_...`), never a public or source-map key: only a server key may assert identity, plan, external org id and trusted edge metadata. Construction throws on any other prefix, because every delivery would otherwise fail after the fact.

### Configuration

| Option | Type | Default | Purpose |
| --- | --- | --- | --- |
| `ingestKey` | `string` | required | Server ingest key (`vis_srv_...`). |
| `endpoint` | `string` | `https://visibling.com/api/v1/ingest` | Ingest URL used without a Service Binding. |
| `serviceBinding` | `{ ingestBatch }` | unset | Same-account RPC transport; skips the network hop. |
| `environment` | `string` | unset | Environment label, capped at 64 characters. Use exactly `internal` (lowercase) to mark internal/test traffic: product analytics excludes it by default. |
| `release` | `string` | unset | Release label, capped at 128 characters. |
| `anonSecret` | `string` | derived from `ingestKey` | Salt for daily anonymous ids. Set it explicitly when several services must agree on ids. |
| `respectNoTelemetry` | `boolean` | `false` | Honour an inbound `X-No-Telemetry: true` request header by skipping the event. |
| `fetch` | `typeof fetch` | global `fetch` | Injectable transport for tests or custom runtimes. |
| `now` | `() => Date` | system clock | Injectable clock for tests and deterministic ids. |

## Delivery model

Every method is fail-soft: transport, JSON and Web Crypto errors are swallowed and never become the host request's failure. Without delivery guarantees there is nothing to retry, so a rejected event is logged and dropped.

Pass a Workers execution context as the last argument to schedule delivery in `ctx.waitUntil`: the method resolves as soon as the work is scheduled, so the response does not wait for the network. Without a context the delivery is awaited.

```ts
export async function handle(request: Request, ctx: ExecutionContext) {
  await visibling.track({ name: "md_render_succeeded", request }, ctx);
  return new Response("ok");
}
```

## `track(input, ctx?)`

Send one product event.

```ts
await visibling.track({
  name: "md_render_succeeded",
  distinctId: user.id,
  path: "/api/v1/md",
  props: { format: "pdf" },
  request,
});
```

`distinctId` is the authenticated user when you have one. For unauthenticated API callers, use `deriveDailyAnonId` instead. When `request` is supplied, its `cf-ray` header and country (`request.cf.country`, else `cf-ipcountry`) travel with the item, so the stored event keeps the caller's edge metadata rather than the metadata of the server's own ingest hop.

## `identify(input, ctx?)`

Write a trusted server-side identity. Unlike the browser client, this is authoritative: `email`, `userName`, `externalOrgId` and `plan` are accepted because the server key proves the caller may assert them. An email that would fail ingest validation is omitted instead of rejecting the item.

```ts
await visibling.identify({
  distinctId: user.id,
  anonId,
  email: user.email,
  plan: account.plan,
  externalOrgId: account.orgId,
  request,
});
```

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

Send a handled server exception as an `error` item with `errorSource: "worker"`. The type, message and stack are normalized; anything thrown, including hostile getters, becomes a safe error item. Use it for failures you catch and recover from; uncaught Worker failures belong in the Tail Worker helper.

```ts
try {
  await render(document);
} catch (error) {
  await visibling.captureException(error, {
    distinctId: user.id,
    path: "/api/v1/md",
    props: { format: "pdf" },
    request,
  }, ctx);
  throw error;
}
```

## `deriveDailyAnonId(request, options?)`

Derive a privacy-preserving id for an unauthenticated caller: `anon:<YYYY-MM-DD>:<16-hex>`. The helper HMAC-SHA256s the caller's IP (from `cf-connecting-ip`, else the first `x-forwarded-for` hop) with a daily salt and `scope`; the raw IP is never returned or transmitted. The id is stable for the UTC day and rotates at midnight. With no IP header it returns `anon:<YYYY-MM-DD>:unknown`, and a runtime without global Web Crypto degrades to the same shared unknown id rather than exposing the address.

```ts
const anonId = await visibling.deriveDailyAnonId(request, { scope: "api" });
await visibling.track({ name: "md_render_succeeded", anonId, request }, ctx);
```

Use `scope` to separate ids between products or tenants that share one ingest key.

## Telemetry opt-out

Explicit server events are sent by default: unlike a browser pageview, they are deliberate. Set `respectNoTelemetry: true`, or pass it per call, to skip any event whose inbound request carries `X-No-Telemetry: true` (also `1` or `yes`).

```ts
const visibling = createVisiblingServer({
  ingestKey: env.VISIBLING_SERVER_KEY,
  respectNoTelemetry: true,
});
```

## Service Binding

When the app and Visibling share a Cloudflare account, bind Visibling's ingest entrypoint and pass it as `serviceBinding`. Delivery then skips the HTTPS hop and the caller's edge metadata travels as RPC metadata instead of proxy headers.

```ts
const visibling = createVisiblingServer({
  ingestKey: env.VISIBLING_SERVER_KEY,
  serviceBinding: env.VISIBLING,
});
```

The binding must expose `ingestBatch(projectKey, batch, meta?)`.
