# `@bucker/node`

Server-side capture: crash handlers, on-disk source context, per-request scopes via
`AsyncLocalStorage`, and an `AsyncLocalStorage` active span for tracing.

> **Distribution note.** The package is build-ready, not yet published. It carries a
> `publishConfig` (pointing at `dist/`, split per subpath) alongside a
> source-pointing top-level `main`/`types`/`exports` — the split matters because
> several other workspace packages import the SDKs by source with no build step,
> while a published consumer cannot compile `./src` and needs the compiled `dist/`.
> `pnpm build` / `prepack` run `scripts/build-package.mjs`, which refuses to finish
> if the built output does not match what `publishConfig.exports` promises. Inside
> the monorepo it resolves through `workspace:*`. What remains is an actual
> `npm publish`, a human decision covered in
> [`sdks/PUBLISHING.md`](../sdks/PUBLISHING.md) — not code readiness.

## Init

Put this in its own module and import it **first** in your entry file, before any
other import. Crash handlers installed after the rest of the app has evaluated do not
cover the rest of the app evaluating.

```ts
// bucker.server.ts
import { init } from '@bucker/node'

export const bucker = init({
  dsn: process.env.BUCKER_DSN ?? '',
  environment: process.env.NODE_ENV ?? 'development',
  release: process.env.BUCKER_RELEASE,
})
```

```ts
// index.ts
import './bucker.server.js' // must stay first
import express from 'express'
```

`create-bucker` writes exactly this pair and injects the import for you.

### Options

All of `ClientOptions` (see [sdk-browser.md](sdk-browser.md#options)) plus:

| Option | Default | Meaning |
| --- | --- | --- |
| `linesOfContext` | SDK default | Lines of on-disk source context per in-app frame. `0` disables the integration |
| `maxBufferBytes` | SDK default | Transport queue ceiling |
| `fetchImpl` | global `fetch` | Testing seam |
| `ignoreErrors`, `denyUrls`, `allowUrls`, `thirdPartyFrames` | — | SDK-side deny lists, evaluated before sampling and counted as `event_processor` drops. See [Filtering noise](sdk-browser.md#filtering-noise-before-it-costs-quota) |

Three options fall back to the environment when they are not passed, so a deploy can
set them without a code change:

| Option | Environment variable |
| --- | --- |
| `release` | `BUCKER_RELEASE` — your build's version or git SHA |
| `environment` | `BUCKER_ENVIRONMENT`, then `production` |
| `serverName` | `BUCKER_SERVER_NAME` |

An empty value counts as unset. **Release health needs a release.** The server
discards every session that does not carry one, so without `release` (or
`BUCKER_RELEASE`) the SDK sends no sessions at all and prints one warning saying so —
crash-free rates, adoption and release comparison are all per release. The Python SDK
reads the same three variable names.

## Default integrations

`globalHandlersIntegration()` and, unless `linesOfContext: 0`,
`contextLinesIntegration()`.

**Crash handlers.** `uncaughtException` is the one hook where an SDK can genuinely
make things worse: install a listener and do nothing else, and you have converted
"crash loudly" into "limp along in an undefined state". So the default is capture →
flush with a bounded timeout (`flushTimeoutMs`, default 2000) → let the process die
exactly as it would have. `exitOnUncaught` defaults to `true` for the same reason.
`unhandledRejection` is captured too.

**Source context.** `contextLinesIntegration` reads ±N lines around each in-app frame
straight off disk at capture time, so a server stack arrives already readable without
any source-map step. `SourceReader` and `addSourceContext` are exported if you need
them directly.

## Express

```ts
import { errorHandler, requestHandler } from '@bucker/node'
import { bucker } from './bucker.server.js'

app.use(requestHandler(bucker))   // before your routes
// … routes …
app.use(errorHandler(bucker))     // after them
```

`requestHandler` forks a scope per request, attaches request context (method, URL,
headers, query string) and a transaction name, then runs the rest of the chain inside
it. `errorHandler` captures with `mechanism: { type: 'middleware', handled: false }`
and passes the error onward untouched — it never swallows. `handled: false` there
means the *request* failed: the error counts against the process's session, but it
does not end that session as crashed — the server is still serving.

An inbound W3C `traceparent` header is adopted as the request scope's
`contexts.trace`, so an error raised while serving a request from a traced caller is
linked to the caller's trace even when this service starts no span of its own.

Client IPs are attached only when `includeIp` is set on the handler options.

## Fastify

```ts
import { fastifyHooks } from '@bucker/node'
import { bucker } from './bucker.server.js'

const hooks = fastifyHooks(bucker)
app.addHook('onRequest', hooks.onRequest)
app.addHook('onError', hooks.onError)
```

Fastify runs the remaining lifecycle inside `onRequest`'s `done()` continuation, so
the `AsyncLocalStorage` context propagates the same way it does through Connect's
`next()`.

## Next.js

Next.js runs on both sides, so it needs both SDKs. Use `instrumentation.ts` beside
your routes directory:

```ts
export async function register() {
  if (process.env.NEXT_RUNTIME !== 'nodejs') return
  const { init } = await import('@bucker/node')
  init({
    dsn: process.env.BUCKER_DSN ?? '',
    environment: process.env.NODE_ENV,
    release: process.env.BUCKER_RELEASE,
  })
}

export async function onRequestError(error: unknown) {
  const { captureException } = await import('@bucker/node')
  captureException(error, { mechanism: { type: 'nextjs.onRequestError', handled: false } })
}
```

The dynamic import matters: an Edge runtime must not pull in the Node SDK at all.
Browser-side init goes in `instrumentation-client.ts` (Next ≥ 15.3) or, on older
versions, one import from the root layout — with `NEXT_PUBLIC_BUCKER_RELEASE` as its
`release`, since only `NEXT_PUBLIC_` variables reach the browser. On Next < 15 you
also need `experimental: { instrumentationHook: true }`.

A capture with the `nextjs.onRequestError` mechanism is treated like Express's and
Fastify's: one failed request, counted as an error on the running session, never a
crash of the server process.

### Tunnel route for the browser SDK

`tunnelRoute({ dsns })` from `@bucker/node/nextjs` is the server half of `@bucker/browser`'s `tunnel`
option; see [Sending through your own origin](sdk-browser.md#sending-through-your-own-origin-tunnel) for
the route file, what it validates and what it costs.

## Crons, feedback and attachments

**Cron check-ins.** `withMonitor` brackets a job with an `in_progress` and a closing `ok` or
`error` check-in (same id, duration in seconds); the callback's result or error passes through.
Pass a schedule and the monitor is created on first sight, under the same rules as the HTTP
check-in route:

```ts
import { withMonitor, flush } from '@bucker/node'

await withMonitor('nightly-export', () => exportEverything(), {
  schedule: { type: 'crontab', value: '0 2 * * *' }, // or { type: 'interval', value: 6, unit: 'hour' }
  checkinMargin: 5, // minutes of grace before "missed"
  maxRuntime: 30, // minutes before "timed out"
  timezone: 'Europe/Madrid',
})
await flush() // a job that exits right away must flush, or its last check-in is a false "missed"
```

`captureCheckIn({ monitorSlug, status, checkInId?, duration? }, monitorConfig?)` is the
lower-level call (start and end in different processes: pass the id back). These ride the same
Sentry-shaped `check_in` envelope item the server already ingests; the HTTP route
(`POST /api/:projectId/monitors/:slug/checkins`) remains the contract for a shell `curl`.

**User feedback.** `captureFeedback({ message, email?, name?, url?, associatedEventId? })` sends a
Sentry-shaped `feedback` item, stored with the same spam scoring as the widget route and linked
to the issue of `associatedEventId` (the id `captureException` returned).

**Attachments.** `addAttachment({ filename, data, contentType? })` attaches a file to the current
scope, and every event captured under it carries it, each file in its own bulk-lane envelope
(never beside the error) naming its `event_id`. The server keeps text and logs (scrubbed with your
project's rules first), minidumps as sent, and screenshots only where the project opted in; other
binaries and credential-shaped names (`.env`, `*.pem`) are refused by name. See
[Sentry SDK compatibility](sentry-compat.md#attachments). `sendAttachments: false` keeps them off
the wire.

**`beforeSendSpan` / `beforeSendLog`.** Like `beforeSend`, for the bulk lane: a hook receives the
serialised span or log record and returns it (changed or not) or `null` to drop it. A drop is a
`before_send` entry in the client report, in the item's own category. A hook that throws changes
nothing.

## Feature flags

Records which flags an error saw, so an issue can answer "which flag broke this". The server reads
`contexts.flags` from every event and rolls it up per issue; this is the producer. Flag SDKs
(LaunchDarkly, Statsig, Unleash, Flagsmith…) come through their **OpenFeature** providers, so one hook
covers them and this package depends on none of them:

```ts
import { OpenFeature } from '@openfeature/server-sdk' // or @openfeature/web-sdk
import { openFeatureHook } from '@bucker/node'

OpenFeature.addHooks(openFeatureHook())
```

Evaluations are recorded on the **current scope**, so on a server a request's flags land on that
request's errors only. A flag evaluated again keeps its latest record; at most 50 are kept (the
server's own ceiling), stalest first out.

**Hook contract v2.** The hook's `finally` stage (OpenFeature 0.9 passes it the full evaluation
details, for a failed evaluation too) records `{ flag, variant, reason, version, provider,
valueDigest, evaluatedAt, requestId?, definitionsLoadedAt? }`, so "variant B of `checkout` at
version 7 raised this error" is a join on stored keys. The **value is customer data**: it is kept
(as `result`) only for booleans and strings of 40 characters or fewer, and anything else, an object,
a number or a longer string, is reduced to its SHA-256 `valueDigest`. A failed evaluation is
recorded with reason `ERROR` and its error code, and suspect ranking ignores it: the caller got the
default, not a decision the flag system made. `version` is read from the provider's
`flagMetadata.version`. With an OpenTelemetry span active, the hook also adds the semantic-convention
`feature_flag.evaluation` event to it (`feature_flag.key`, `feature_flag.result.variant`,
`feature_flag.result.reason`, `feature_flag.provider.name`, `feature_flag.version`), which is how a
trace shows which variants a request saw: the server folds the events into one `bucker.flags`
attribute on the trace's local root span, and spans from a non-Bucker OpenTelemetry SDK that carry
`feature_flag.*` attributes or events are read the same way. Without OpenFeature, call
`recordFlagEvaluation(flag, result)` yourself (the v1 shape, no variant). The Python and Dart hooks
are not part of this release.

## Serverless, edge and more frameworks

Each is an explicit wrapper or middleware over the same request scope Express uses: no preload
flag, no `--import` ordering to get right.

**AWS Lambda** (`@bucker/node/lambda`). A Lambda freezes the moment the handler returns, so the
wrapper's job is ordering: open a scope, run the handler, capture a throw, **flush before
returning**, bounded by the time Lambda says is left, so the flush can never be what times the
function out. Async and legacy `(event, context, callback)` handlers both work, and the original
error is rethrown. API Gateway v1/v2, ALB and function-URL events carry request context (headers
allowlisted, query values masked); other events (SQS, S3, EventBridge) are named by the function.

```ts
import { init } from '@bucker/node'
import { wrapHandler } from '@bucker/node/lambda'

init({ dsn: process.env.BUCKER_DSN, signalHandlers: false }) // Lambda sends SIGTERM on recycle
export const handler = wrapHandler(async (event, context) => {
  /* ... */
})
```

**Cloudflare Workers, Vercel Edge, Deno, Bun** (`@bucker/sdk-core/edge`). A `fetch`-only entry with
no Node built-ins (a test bundles it for the browser platform to prove it) and a
`waitUntil`-aware flush: with a platform context the flush is registered with the runtime, so the
response is not delayed and the isolate is kept alive until it settles. Without that a
fire-and-forget `fetch` is cancelled at response time, which is the Vercel `waitUntil` trap.

```ts
import { wrapFetch } from '@bucker/sdk-core/edge'

export default {
  fetch: wrapFetch((request, env, ctx) => app.fetch(request, env, ctx), (env) => ({
    dsn: env.BUCKER_DSN,
    release: env.BUCKER_RELEASE,
  })),
}
```

With no ambient async context, the request scope is **explicit**: `wrapFetch` and
`captureEdgeError(client, error, request, ctx)` apply it to that request's event directly, so
concurrent requests in one isolate cannot mix. Sessions are not tracked (an isolate is not a user
session). For Hono on Workers, call `captureEdgeError` from `app.onError`, since Hono turns a throw
into a response before `wrapFetch` sees it. This entry is verified against fakes in this repo (no
workerd, Deno or Bun in the test environment); smoke-test the runtime you deploy to.

**Hono on Node** (`@bucker/node/hono`): `app.use('*', honoMiddleware(client))`. It reads the error
Hono leaves on `c.error` as well as a throw that escapes.

**Koa** (`@bucker/node/koa`): `app.use(koaMiddleware(client))` **first**, and optionally
`app.on('error', koaErrorHandler(client))` for what a custom error middleware swallowed.

**NestJS** (`@bucker/node/nestjs`), no `@nestjs/*` dependency. Either add `captureNestException` in
front of Nest's own `BaseExceptionFilter`, or register
`app.useGlobalFilters(new BuckerExceptionFilter({ client }))` (which also answers the request, or
hands it to a `delegate` you give it).

All of them capture a 4xx (`HttpException`, `ctx.throw(404)`, Hono's `HTTPException`) **not at
all**, capture an error object **once** however many hooks see it, and use mechanism
`request.<framework>` so a failed request never ends the process session as a crash.

## Tracing

`@bucker/sdk-core/tracing`'s `withSpan`, `startSpan`, `getActiveSpan` and
`getTraceHeaders` work against the client `init()` returns, and under `@bucker/node`
the active span follows the async chain (`AsyncLocalStorage`) rather than a stack —
so two concurrent requests each see their own span across every `await`, and the
`traceparent` a request sends downstream names its own trace. An error captured
while a span is active carries that span's `trace_id` and `span_id`, at the top level
and in `contexts.trace`, which is what links it to the trace and to the logs on it.

## GenAI adapters

`@bucker/node/integrations/genai` records model calls as `gen_ai.*` spans. Nothing patches
globally and no provider SDK is imported: you hand each adapter your client (or callback slot)
and a recorder, session or turn from `@bucker/sdk-core/genai`. Every adapter records the host's
own errors and re-throws them untouched, and a recording failure is a debug line, never an
exception in your request.

| Framework | Adapter | What it hooks |
| --- | --- | --- |
| OpenAI | `instrumentOpenAI(client, target)` | `chat.completions.create`, `responses.create` |
| Anthropic | `instrumentAnthropic(client, target)` | `messages.create` (incl. streams) |
| LangChain | `langChainCallbackHandler(target)` | callbacks |
| Vercel AI SDK | `genAiMiddleware(target)` | language-model middleware |
| LangGraph | `langGraphCallbackHandler(target)`, `withLangGraph(config, handler)` | graph callbacks; one turn per graph run |
| AWS Bedrock | `instrumentBedrock(client, target)` | `send()` for Converse, ConverseStream, InvokeModel |
| Google Gen AI | `instrumentGoogleGenAI(client, target)` | `models.generateContent` and `generateContentStream` |
| OpenAI Agents SDK | `openAiAgentsTraceProcessor(target)` | `addTraceProcessor(...)` |
| Claude Agent SDK | `instrumentClaudeAgent(query, target)` | the `query()` message stream |

LiteLLM's proxy speaks the OpenAI wire protocol, so `instrumentOpenAI` on the client that talks to
it records the proxied calls. Pydantic AI and the Python frameworks are covered in
[the Python SDK page](sdk-python.md).

## Automatic spans (`@bucker/node/otel`)

```ts
import * as Bucker from '@bucker/node'
import { initOtel } from '@bucker/node/otel'

Bucker.init({ dsn })
await initOtel({ serviceName: 'checkout' })   // before the modules it instruments are imported
```

HTTP, undici, express, fastify, pg, mysql, redis, graphql and the rest of OpenTelemetry's
maintained instrumentations, exported to Bucker over OTLP (`POST /v1/traces` on your DSN's host,
authenticated with `Authorization: DSN <dsn>`; see [OTLP](otlp.md)). Bucker's own `withSpan` stays
the API for spans you write by hand, and both land in the same trace store.

The OpenTelemetry packages are **optional peer dependencies** of `@bucker/node`: declared in
`peerDependencies` with `peerDependenciesMeta: { optional: true }`, so npm, Yarn and pnpm check the
version ranges of whatever you install but never install them for you, and an app that does not use
`@bucker/node/otel` carries none of them. `initOtel()` loads them by dynamic import. Install the
seven to turn the bridge on:

```
npm install @opentelemetry/api @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-base \
  @opentelemetry/exporter-trace-otlp-http @opentelemetry/resources \
  @opentelemetry/instrumentation @opentelemetry/auto-instrumentations-node
```

(`pnpm add` / `yarn add` take the same list.) The declared ranges are `@opentelemetry/api ^1.3.0`,
the SDK packages (`sdk-trace-node`, `sdk-trace-base`, `resources`) `>=1.15.0 <3`, so both the 1.x
and the 2.x SDK lines work, and the 0.x packages (`exporter-trace-otlp-http`, `instrumentation`,
`auto-instrumentations-node`) from `0.41.0`/`0.40.0` up. If you pass your own `instrumentations`, or
set `autoInstrument: false`, the first four are enough: `api`, `sdk-trace-node`, `sdk-trace-base` and
`exporter-trace-otlp-http` (plus `resources` for the service attributes). You do not need the gRPC
exporter; the bridge exports over OTLP/HTTP.

When a package is missing, `initOtel()` returns `{ enabled: false, missing: [...] }` and warns once
with that install line rather than quietly doing nothing. Errors captured while an OTel span is
active carry its `trace_id`/`span_id`, so an issue links to the automatic trace. Defaults: the
exporter's own requests to Bucker are excluded from the http instrumentation, and the `fs`
instrumentation is off. Override with `instrumentationConfig`, send to a Collector with
`endpoint`, or pass your own `instrumentations`. `autoInstrument: false` registers the provider
and exporter only.

### Inside this repository: optional peers stay optional

pnpm 11 with this workspace's `auto-install-peers=true` installs every `peerDependencies` entry of a
WORKSPACE project into that project, `optional` or not (it honours `optional` only for registry
packages). Declared plainly, the seven packages above pulled `auto-instrumentations-node` and
everything behind it into `pnpm-lock.yaml`: about 1,500 lines, gRPC, `msgpackr-extract` with a
native build script, and a re-resolved `@sentry/node` v10 compatibility fixture. `code/pnpmfile.cjs`
removes optional peers from the manifest pnpm resolves for workspace projects only; the
`package.json` on disk, and so the published manifest, keeps the declaration. The lockfile cost is
one `pnpmfileChecksum` line, and `test/otel.test.ts` pins both halves (declared optional, not
resolved). The bridge's own tests inject fake modules, so none of these packages is installed here.
`bullmq` and `node-cron` are not declared: the cron integrations take the library as an argument.

## Cron check-ins for `node-cron` and BullMQ

`@bucker/node/integrations/crons` brackets scheduled work in check-ins (`in_progress`, then `ok` or
`error` with the duration), so a job that stops arriving is a missed check-in. It is opt-in, takes
the library as an argument, and depends on neither package:

```ts
import cron from 'node-cron'
import { instrumentNodeCron } from '@bucker/node/integrations/crons'

const scheduler = instrumentNodeCron(cron)
scheduler.schedule('0 2 * * *', nightlyReport, { name: 'nightly-report', timezone: 'UTC' })
```

A task needs a `name`, which becomes the monitor slug. A task with no name is scheduled but not
monitored, and the SDK says so once. The expression is the monitor's schedule, and the monitor is
created on the first check-in. A six-field (seconds) expression has no monitor equivalent, so it
reports without a schedule.

```ts
import * as bullmq from 'bullmq'
import { instrumentBullMQ } from '@bucker/node/integrations/crons'

const { Worker } = instrumentBullMQ(bullmq)
new Worker('mail', async (job) => sendDigest(job.data), { connection })
```

Only jobs created by a repeat rule (`opts.repeat`, so `upsertJobScheduler` and `repeat` options) are
monitored; a one-off job runs as before. `pattern` becomes a crontab and `every` an interval in whole
minutes (under a minute, no schedule). The slug is `bullmq-<queue>-<scheduler id or job name>`;
pass `{ slug: (job, queue) => string | null }` to choose your own or to skip a job. A processor
given as a file path runs in a sandbox and is left alone; wrap it yourself with
`monitorBullMQProcessor`. `loadNodeCron()` and `loadBullMQ()` import the library on request and
return `null` with one warning when it is not installed. The Python equivalent for Celery beat is
`install(app, monitor_beat_tasks=True)` ([Python SDK](sdk-python.md)).

## Capturing by hand

Same surface as the browser SDK: `captureException`, `captureMessage`,
`addBreadcrumb`, `setUser`, `setTag`, `setExtra`, `setContext`, `flush`, `close`,
`getCurrentScope`. `getRequestScope()` additionally returns the scope for the request
currently in flight.

## Not built yet

Opt-in **local-variable capture** is deliberately absent. The seam exists —
`StackFrame.vars` in the shared schema plus the event-processor hook that
`contextLinesIntegration` already uses — but shipping variable capture before the
entropy- and format-aware masking (JWT / AWS key / Luhn / email) and the redaction
manifest is how an SDK exfiltrates a customer's secrets. It is staged after masking,
not before.

Also absent: automatic span creation per request (to join an incoming trace, give
`withSpan` a `parent` of `continueTrace({ traceparent, tracestate })` read from the
request's headers), cron monitoring, and profiling.
