@unhandled/node
v0.9.6
Published
Unhandled SDK for any Node.js app: traces, logs, metrics, exceptions and analytics over OTLP
Readme
@unhandled/node
Sends traces, logs, metrics, exceptions and analytics events from any Node.js 24+ app to Unhandled over OTLP/HTTP. It builds the OpenTelemetry Node SDK with the auto-instrumentations, so HTTP servers, outgoing requests, databases, Redis and loggers are traced without code changes. Framework packages such as @unhandled/agent-adonisjs add route names, users and error handler hooks on top.
Start
The DSN comes from the service settings page.
UNHANDLED_DSN=https://[email protected]/0b4f6c2e-8a1d-4c3e-9f7a-1234567890ab \
node --import @unhandled/node/register server.jsregister hooks ES module loading, then calls init() with options from the environment only: UNHANDLED_DSN, UNHANDLED_ENV (production, staging or development, else APP_ENV when it names one of those, else derived from NODE_ENV) and OTEL_SERVICE_NAME.
To pass options in code, call init() before importing anything you want traced:
import { init } from '@unhandled/node'
init({ dsn: process.env.UNHANDLED_DSN, serviceName: 'checkout', samplingRatio: 0.5 })init() returns the running client, or null when nothing would be exported (no DSN, NODE_ENV=test, enabled: false) and debug is off. Calling it again returns the same client. Without register, only CommonJS modules required after init() are patched. ES modules need the hook.
Under NODE_ENV=test nothing starts unless enabled: true is set.
Options
dsn, environment, serviceName, serviceVersion, resourceAttributes, enabled, dev + endpoint, legacy apiKey + endpoint, destinations (extra OTLP endpoints), compression, batch, samplingRatio or sampler, sampling (per-job rules with Sample), debug (prints spans to the console), hostMetrics, http (ignored URLs, URL sanitizing, body capture with redaction), ignoreOptionsRequests, instrumentations, integrations, spanProcessors, logRecordProcessors, metricReaders, ignoreExceptions, ignoreStatuses, ignoreCodes, processHandlers, sourceContext (root, includeNodeModules) and shutdownTimeoutMillis (default 5000, the longest flush() and shutdown() wait).
URL sanitizing is on by default. On SERVER and CLIENT spans, url.full, url.path, url.query, http.url and http.target lose secret query values (token, code, state, signature, api_key and the rest of the body redaction names) and secret path segments (JWTs, email addresses, keys with a known secret prefix such as sk_live_ or ghp_, random tokens of 32 or more mixed-case characters with a digit, ids of 8 or more characters with a digit in the 2 segments after a reset, verify, invite, token, session, share, oauth, key, hook or download segment, Slack webhook secrets, and ;jsessionid= values). /reset/9f86d081884c7d659a2feaa0c55ad015?token=x&page=2 is exported as /reset/REDACTED?token=REDACTED&page=2. Ids such as /orders/550e8400-e29b-41d4-a716-446655440000 stay; strict: true keeps these rules and also replaces UUIDs and opaque ids. http.sanitizeUrls: { queryParams } adds names, sanitize(url) replaces the rules, and sanitizeUrls: false (or UNHANDLED_SANITIZE_URLS=false) turns it off. Before this release sanitizing was opt-in and queryParams replaced the built-in names.
Source lines are read only for files a real stack frame names: never from lines in the error name or message, only .js .mjs .cjs .ts .mts .cts .jsx .tsx files whose real path is under sourceContext.root or UNHANDLED_SOURCE_ROOT (by default the entry script's project: its nearest package.json directory, or the workspace root above it, or the working directory when that contains it and is not /), never dotfiles such as .env or dot directories other than build output (.next, .nuxt, .output, .mastra, .svelte-kit, .vercel), never /proc or /etc, never node_modules unless sourceContext.includeNodeModules is true (which also covers pnpm's node_modules/.pnpm), and never files over 1 MiB.
instrumentations takes a config per auto-instrumentation name, { enabled: false }, or an Instrumentation instance. net, dns, socket.io, pg, mysql and mysql2 are off unless you turn them on. Health checks, metrics endpoints, static files, Vite dev assets and OPTIONS requests produce no server spans. HTTP and database spans use the stable OpenTelemetry attribute names (http.request.method, url.path, db.query.text).
With processHandlers (on by default), an uncaught exception is reported with handled: false, printed, flushed for up to 2 s, and the process exits with code 1. An unhandled rejection is reported and then behaves as Node's --unhandled-rejections mode says. If the app registers its own listener, the SDK reports and leaves the decision to it.
API
import { Unhandled, record } from '@unhandled/node'
Unhandled.setUser({ id: user.id, email: user.email })
Unhandled.captureException(error, { tags: { area: 'billing' }, extra: { orderId } })
Unhandled.captureMessage('quota almost used', 'warning')
Unhandled.track('checkout_completed', { plan: 'pro' })
Unhandled.trackRevenue({ amount: 1999, currency: 'usd', product: 'pro', subscription: { id: 'sub_1', interval: 'month' } })
Unhandled.identify(user.id, { plan: 'pro' })
await record('report.generate', async (span) => buildReport())
await Unhandled.flush()
await Unhandled.shutdown()setUser writes user.* on the active span and on the request's SERVER span.
identify(userId, properties?) is the opt-in for user-level analytics. It validates, sends a profile update, and inside a request binds the id to that request: it sets user.id on the spans like setUser({ id }), and every track() in the same request carries user.id. Outside a request it only sends the profile update, because a server never has a process-wide user. setUserProperties(properties) updates the bound user's profile and returns { ok: false, error: { code: 'no_user' } } without one. reset() unbinds the request's user. trackRevenue({ amount, currency, id?, product?, subscription?, properties? }) records a purchase, renewal or refund with amount as an integer in the currency's minor unit (1999 is $19.99, negative for a refund) and subscription as { id, interval, intervalCount? } for MRR; it returns { ok: true, eventId } (the given id when set) or { ok: false, error } and carries the request's user.id like track(). Pass the payment provider's charge id as id so a retried call counts once. The event name revenue is reserved for it, so track('revenue') returns reserved_name. getVariant(experiment, variants, { userId? }) returns the variant of the request's identified user (or userId) in an experiment, the same one every SDK picks, and records an experiment_exposure event; without a user it returns the first variant and records nothing. trackExposure(experiment, variant, { userId? }) records a variant your app assigned itself and returns whether it was sent. All three return { ok: true } or { ok: false, error } and never throw. Properties follow the track() limits except that only the unhandled. prefix is reserved, so email and name are allowed. @span() and @spanAll() decorators, getCurrentSpan, setAttributes, recordEvent, injectTraceContext and extractTraceContext are exported too. Integration packages import their types from @unhandled/node/types.
Building a framework package
@unhandled/node/framework is the kit framework layers use. Every function is a no-op when no client is running or the request has no SERVER span.
import {
captureRequest,
captureResponse,
reportException,
setRoute,
} from '@unhandled/node/framework'
// in the framework's routing hook
setRoute('/orders/:id', 'GET')
captureRequest({ method, url, contentType, headers, raw })
// in its error handler
reportException(error, { mechanism: 'express.error_handler', handled: false, user })getClient()returns the running client ({ config, flush, shutdown }) ornull.serverSpan()returns the SERVER span of the current request. It reads the RPC metadata the HTTP instrumentation attaches to the context, and otherwise falls back to the open SERVER span of the active trace, which covers frameworks such as Next.js that start their own.setRoute(route, method?)setshttp.route, renames the spanMETHOD routeand updates the RPC route. Withoutmethodit reads the span's request method.captureRequest(input)andcaptureResponse(input)apply the configured body and header capture with redaction. Nothing is recorded unless the user turned capture on.capturesBody(side)returns whether the current request captures the'request'or'response'body. Check it before reading or serializing a body, so a side nobody captures costs nothing.reportException(error, { mechanism, handled, shouldReport?, user?, level?, tags?, extra? })skips errors matched byignoreExceptions,ignoreStatusesandignoreCodes, and reports each error object once.mechanismis a free string, usually<framework>.<hook>.- A framework package identifies itself by passing
frameworkLayer: { sdk: { name, version }, framework }toinit(). The resource then carriesunhandled.sdk.name,unhandled.sdk.versionandunhandled.framework.name.frameworkLayer(new URL('../package.json', import.meta.url), 'express')builds it from the package's own manifest. startWithEsmHook(load)from@unhandled/node/hookregisters the ES module hook, runsload, and waits until the hook has every instrumented module name. A package's ownregistermodule calls it with aloadthat imports itsinitdynamically, since anything imported before the hook loads unpatched.resolveConfig(options, env)andstart(config, { env, cwd })splitinit()in two for layers that load their config before starting the SDK.
For AI agents
A coding agent can install this package, check that its data arrives and fix the errors it reports through the Unhandled MCP server at https://unhandled.net/mcp. In Claude Code, the Unhandled plugin adds that server plus skills for instrumenting a service, fixing a production error with a failing test first and verifying a deploy:
claude plugin marketplace add treboryx/unhandled
claude plugin install unhandled@unhandledCodex, Cursor, Gemini CLI and other agents connect to the same URL. Coding agents has the setup for each one and an AGENTS.md section to add to your repository.
