@unhandled/agent-adonisjs
v0.7.6
Published
Unhandled for AdonisJS: first-party layer on @unhandled/node for routes, auth users, the exception handler, Ace commands, mail and queues
Readme
@unhandled/agent-adonisjs
Sends traces, logs, metrics, exceptions and analytics events from an AdonisJS 6.2+ or 7 app to Unhandled over OTLP/HTTP. It is the AdonisJS layer on top of @unhandled/node, which owns the OpenTelemetry Node SDK. This package adds route names, the signed-in user, the exception handler hook, Ace command spans, mail spans and @adonisjs/queue spans. Every @unhandled/node option works in config/unhandled.ts.
Install
node ace add @unhandled/agent-adonisjsnode ace add installs the package with your package manager and runs its configure hook. AdonisJS 6.2 has no add command (it arrived in 6.3), so install the package and run node ace configure @unhandled/agent-adonisjs there.
The configure hook:
- creates
config/unhandled.tsandotel.ts - adds
import '../otel.js'as the first import ofbin/server.tsandbin/console.ts(skipped when already there) - registers the provider in
adonisrc.tsand the middleware as the first router middleware - adds
APP_ENVandUNHANDLED_DSNto.envandstart/env.ts, leaving an existing DSN alone
otel.ts must stay the first import. Anything imported before it loads unpatched and produces no spans.
The hook stops without changing anything when otel.ts starts @adonisjs/otel, and the provider refuses to boot beside the @adonisjs/otel provider. Pick one package: see Migrate from @adonisjs/otel.
Paste the DSN from the service settings page:
UNHANDLED_DSN=https://[email protected]/0b4f6c2e-8a1d-4c3e-9f7a-1234567890abStaying on @adonisjs/otel
Apps that keep @adonisjs/otel don't need this package. Install @unhandled/otel-lean instead: it has the same preset and installs neither the agent nor the @unhandled/node SDK. In config/otel.ts:
import { unhandledDestinations } from '@unhandled/otel-lean/otel_preset'
export default defineConfig({
// ...
destinations: unhandledDestinations({ dsn: env.get('UNHANDLED_DSN'), environment: env.get('APP_ENV') }),
})Passing destinations switches export away from the OTEL_* variables: the OpenTelemetry Node SDK builds no exporter from OTEL_EXPORTER_OTLP_* once a destination supplies its own. If your .env has both UNHANDLED_DSN and OTEL_* variables, everything goes to the DSN and the OTEL_* endpoint receives nothing.
This covers export only; exception capture, mail and Ace spans and job sampling need the agent.
@unhandled/agent-adonisjs/otel_preset, /execution_context and /knex_pool_wait re-export the @unhandled/otel-lean subpaths, so imports from 0.4.0 keep working. They load without the SDK, but installing this package still installs it. See the @unhandled/otel-lean README for the connection pool wait, the web or background context and the @opentelemetry/instrumentation pin.
Configuration
// config/unhandled.ts
import { defineConfig } from '@unhandled/agent-adonisjs'
export default defineConfig({})otel.ts loads this file before the app boots, and defineConfig() reads UNHANDLED_DSN, APP_ENV and UNHANDLED_ENV from the process environment and the .env files on its own. Don't import #start/env here: Env.create copies .env into process.env that early, and node ace test then passes those values to the test process ahead of .env.test. Running node ace configure @unhandled/agent-adonisjs replaces the config that versions up to 0.7.4 generated.
| Option | Default | Effect |
| --------------------------------------------------- | -------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| dsn | none | Endpoint, API key and service id. Without it (and without extra destinations) nothing is exported. An invalid DSN disables export with a warning. |
| dev | false | Ignores the DSN. Exports only when endpoint points at a local collector. |
| apiKey, endpoint, serviceName | none | Legacy setup: sends x-api-key and x-unhandled-env to endpoint. dsn wins when both are set. endpoint also overrides the DSN host. |
| environment | UNHANDLED_ENV, then APP_ENV or NODE_ENV if it is production, staging or development, else development | Aliases such as prod are read with a warning; any other value in the option or UNHANDLED_ENV turns export off with a warning. |
| serviceVersion | detected | See version detection below. |
| enabled | true, false when NODE_ENV=test | Turns the SDK off. |
| debug | false | Also prints every span to the console. |
| samplingRatio | 1 | Head sampling ratio in [0, 1]. Forced to 1 when sampling is set. Below 1, kept spans carry unhandled.sampling.ratio. |
| sampling(ctx) | none | Per-job sampling, see below. |
| compression | true | gzip on every signal. 'gzip' and 'none' still work. |
| batch | 512 items, 5 s delay, 30 s timeout, queue of 2048 | Span and log batch processors. |
| shutdownTimeoutMillis | 5000 | Deadline for flush() and shutdown(). Neither rejects; unsent telemetry is dropped at the deadline. |
| hostMetrics | { enabled: true } | CPU, memory and network metrics. false also works. |
| destinations | [] | Extra OTLP endpoints, each receiving traces, metrics and logs next to the DSN destination. |
| integrations | [] | Integration packages such as @unhandled/instrumentation-bullmq. Names must be unique. |
| mail | { enabled: true } | Mail spans. false turns them off. |
| queue | { enabled: true, executionSpanLinkMode: 'link' } | Job spans for @adonisjs/queue. 'parent' makes executions children of the dispatch span. |
| cli | include *, exclude make:*, generate:*, queue:work, queue:listen | Ace command spans. Long-running commands are never traced. |
| ignoreOptionsRequests | true | Drops CORS preflight spans. |
| http | see below | Ignored URLs, URL sanitizing and body capture. |
| ignoreExceptions, ignoreStatuses, ignoreCodes | [] | Error classes, HTTP statuses and error codes the exception handler hook does not report. |
| userContext | reads id and role from ctx.auth.user | email: true also sends the email (personal data), resolver(ctx) returns the user (extra keys become user.<key>), false turns it off. |
| instrumentations | net, dns, socket.io, pg, mysql and mysql2 off | Per auto-instrumentation config, { enabled: false }, or an Instrumentation instance. |
| processHandlers | true | Reports uncaught exceptions and unhandled rejections, then keeps Node's crash behavior. |
The keys ai, mastra, bullmq and cache are not agent options. Passing them logs a warning that names the package to install instead, and they are ignored.
import { defineConfig, destinations } from '@unhandled/agent-adonisjs'
export default defineConfig({
destinations: [
destinations.otlp({
name: 'grafana',
url: 'https://otlp-gateway.grafana.net/otlp',
headers: { Authorization: `Basic ${btoa('id:key')}` },
}),
],
})Service name and version
With a DSN the ingest server takes the service from the DSN. For other destinations the name comes from serviceName, OTEL_SERVICE_NAME, APP_NAME, the package.json name without its npm scope, then unknown_service.
The version comes from the first usable value of serviceVersion, UNHANDLED_VERSION, APP_VERSION, the platform revision (Vercel, Render, Railway, Heroku, Coolify, Dokku, Cloud Run), the CI commit (GitHub Actions, GitLab CI, CircleCI, Bitbucket Pipelines, Buildkite, Cloudflare Workers Builds), then the local .git HEAD. Placeholders (0.0.0, 0.0.1, 1.0.0, unknown, dev, latest, empty) are skipped. The resource gets service.version, unhandled.service.version.source (config, env:UNHANDLED_VERSION, platform:render, ci:github_actions, git, ...) and vcs.ref.head.revision when a commit SHA is known.
HTTP
defineConfig({
http: {
ignoredUrls: ['/internal/*'],
sanitizeUrls: { queryParams: ['invite'], censor: 'REDACTED' },
captureBodies: {
incoming: { request: { enabled: true }, response: { enabled: true } },
outgoing: { request: { enabled: true, maxBodySize: 16_384 } },
redact: { bodyKeys: ['pin'], headers: ['x-tenant'] },
transform: (record) => {
record.http.body = { ...record.http.body, trimmed: true }
},
},
},
})ignoredUrlsadd to the built-in list of health checks, metrics endpoints, static files and Vite dev assets./adminand/admin/*cover the path and everything below it, other*are globs.sanitizeUrlsis on by default. It rewriteshttp.url,url.full,url.path,http.targetandurl.queryon server and client spans: secret query values (token,code,state,signature,api_keyand the body redaction names) and secret path segments (JWTs, email addresses, keys with a known secret prefix such assk_live_orghp_, 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) becomeREDACTED. Ids such as UUIDs and hashes stay;strict: truekeeps these rules and also replaces UUIDs and opaque ids.queryParamsadds names,sanitize(url)replaces the whole URL instead, andsanitizeUrls: falseturns it off. Before this release it was opt-in andqueryParamsreplaced the built-in names.- Body capture is off until
enabledor a per-sideenabledis set. Onlyapplication/jsonandapplication/x-www-form-urlencodedbodies are kept. Built-in keys (password,token,code,access_token,refresh_token,authorization,secret,api_key,client_secret,cookie,session,otp,cvv,card_number,ssnand more, matched case and separator insensitively) are always redacted and your lists add to them. Redaction runs beforetransform; returningnullfromtransformskips the capture. Bodies are cut tomaxBodySizebytes (default 10 000) and stored asunhandled.http.request.bodyandunhandled.http.response.body. Raw text longer than 64 KiB, or thanmaxBodySizewhen that is larger, is not parsed. The span getsunhandled.http.request.body_omittedorunhandled.http.response.body_omittedset totoo_large. - Incoming bodies are read from the Adonis request and response in the middleware. Outgoing capture hooks
node:httpandnode:httpsonly, notfetchor undici. - Options you set under
instrumentations['@opentelemetry/instrumentation-http']merge with these. YourignoreIncomingRequestHook,requestHookandresponseHookrun in addition to the built-in ones.
Job sampling
import { defineConfig, Sample } from '@unhandled/agent-adonisjs'
defineConfig({
sampling: (job) => {
if (job.name === 'HeartbeatJob') return Sample.never()
if (job.name === 'SendNewsletterEmail') return Sample.rate(0).keepErrors({ maxSpans: 500 })
return Sample.default()
},
})The callback gets { kind: 'job', system, name, queue?, jobId?, attempt? }. Jobs from @adonisjs/queue are recognised from their consumer span; integrations such as BullMQ ask before the worker body runs, so a dropped job creates no spans at all. keepErrors() buffers the job's spans until the root ends and exports them only if something failed, root first. It buffers at most maxSpans spans, by default one less than batch.maxQueueSize (2047). Later spans are dropped, and the root gets unhandled.sampling.truncated=true and unhandled.sampling.dropped_spans=<n>.
What gets recorded
- HTTP server spans named
GET /users/:idwithhttp.route,adonis.route.name, the status and the signed-in user. - Database, Redis, outgoing HTTP and the other Node auto-instrumentations.
- Mail sends (including queued ones) as CLIENT spans named
email send <mailer>withemail.system=adonisjs-mail,email.operation=send,email.transport,email.message.subject,email.message.from,email.message.to(JSON array),email.recipient_countandemail.message.id. Failures record the exception and set ERROR status. - Queue dispatch and execution spans from
@adonisjs/queue. - Ace commands as
cli <name>spans withentry_point.type=cli,cli.command.name,cli.command.description,cli.args.*andcli.flags.*. - Exceptions reported by the Adonis exception handler or failed Ace commands (an app
report()override must still callawait super.report(error, ctx)), as log records withunhandled.log.source=exception_reporter, the cause tree and source lines for in-app frames. Source lines come only from.js/.tssource files under the app root (sourceContext.root), never from paths named in an error message, dotfiles such as.env, ornode_modulesunlesssourceContext.includeNodeModulesistrue. - Pino logs and runtime and host metrics.
API
import { Unhandled } from '@unhandled/agent-adonisjs'
Unhandled.setUser({ id: user.id, email: user.email, name: user.fullName })
Unhandled.captureException(error, {
user: { id: 7 },
tags: { area: 'billing' },
extra: { orderId },
})
Unhandled.captureMessage('quota almost used', 'warning')
Unhandled.captureMessage('import finished', { level: 'info', tags: { source: 'csv' } })
Unhandled.track('subscription_started', { plan: 'pro', seats: 3 })
Unhandled.trackRevenue({ amount: 1999, currency: 'usd', product: 'pro', subscription: { id: 'sub_1', interval: 'month' } })
Unhandled.identify(user.id, { plan: 'pro' })
Unhandled.setUserProperties({ seats: 3 })setUser writes user.id, user.email and user.name on the active span and on the request's SERVER span. The SERVER span is found through the OpenTelemetry RPC metadata the HTTP instrumentation attaches to the request context, so the call works from nested spans in controllers and services. Never put secrets in user fields.
identify is the opt-in that links analytics events to a user. It binds the id to the current request only: later track() calls in that request carry user.id, and the request span gets user.id like setUser({ id }). Nothing is taken from the auth user automatically. setUserProperties updates the bound user's profile (no_user without one) and reset unbinds. They are also exported from @unhandled/agent-adonisjs/helpers.
trackRevenue({ amount, currency, id?, product?, subscription?, properties? }) records a purchase, renewal or refund. amount is an integer in the currency's minor unit (1999 is $19.99), negative for a refund. subscription is { id, interval: 'day' | 'week' | 'month' | 'year', intervalCount? } and feeds MRR. Like track, it returns { ok: true, eventId } or { ok: false, error } and carries the bound user.id. 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) and records an experiment_exposure event; every SDK picks the same variant for the same user. Without a user it returns the first variant and records nothing. trackExposure(experiment, variant, { userId? }) records a variant you assigned yourself.
captureMessage levels are debug, info (default), log, warning, error and fatal, sent as unhandled.message.level. It never throws. captureException sends unhandled.message.level=error.
Custom spans
import { record, setAttributes } from '@unhandled/agent-adonisjs/helpers'
import { span, spanAll } from '@unhandled/agent-adonisjs/decorators'
await record('report.generate', async (active) => {
active.setAttribute('report.type', 'monthly')
return buildReport()
})
@spanAll({ prefix: 'user' })
class UserService {
findById(id: number) {}
}./helpers re-exports getCurrentSpan, setAttributes, recordEvent, injectTraceContext, extractTraceContext, setUser, identify, setUserProperties, trackRevenue, getVariant, trackExposure and reset. Its record and handleError, and the @span / @spanAll decorators, add an exception event with unhandled.exception.frames (source lines around in-app frames) and unhandled.exception.cause_chain (every cause, including AggregateError children), set ERROR status, end the span and rethrow.
Background spans
A query or outgoing call that runs outside a request, job or Ace command becomes the root of its own trace and shows up as a background span. To fix it:
- Wrap polling loops, timers and hand-rolled workers in
record('sync.tick', async () => { ... })so their queries get a parent. - Keep work inside the span's async callback. When a library loses context (emitters, pools, callbacks), run the callback with
context.with(savedContext, fn)from@opentelemetry/api. - Keep
import '../otel.js'the first import ofbin/server.tsandbin/console.ts. Modules loaded before it are not instrumented. - Silence intentional noise (health probes, tight polling) with
context.with(suppressTracing(context.active()), fn)usingsuppressTracingfrom@opentelemetry/core.
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.
