@aient/otel
OpenTelemetry for Node.js/Next.js/Edge. Works out of the box, highly configurable.
Quick Start (3 lines)
npm install @aient/otel @opentelemetry/api @opentelemetry/api-logs
// instrumentation.ts (Next.js 13.4+)
import { registerOTel } from '@aient/otel'
export function register() {
registerOTel({ serviceName: 'my-app' })
}
Browser-propagated app.installation.id, enduser.id, and enduser.pseudo.id are untrusted correlation hints. @aient/otel projects only those safe browser identity fields, then applies attributesFromHeaders, so a gateway/session-derived trusted enduser.id wins. Never map a freely client-set header as trusted identity, and never authorize from baggage.
Done. Traces go to https://ingest.aient.ai/v1/traces by default, logs to /v1/logs.
Local Development
For local development with a collector on localhost, set the env var:
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
Custom Endpoint (programmatic)
To set the endpoint in code instead of env vars, use exporterUrl:
registerOTel({
serviceName: 'my-app',
exporterUrl: 'https://my-collector.example.com', // SDK appends /v1/traces and /v1/logs
exporterHeaders: { 'x-api-key': 'your-key' }, // optional custom headers
})
Full Example (all options)
import { registerOTel, OTLPHttpJsonTraceExporter, OTLPHttpJsonLogsExporter } from '@aient/otel'
import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base'
import { BatchLogRecordProcessor } from '@opentelemetry/sdk-logs'
export function register() {
registerOTel({
// Identity
serviceName: 'my-app',
attributes: {
'app.version': process.env.npm_package_version,
},
// Release metadata (CRITICAL for source mapping)
// Config takes precedence over env vars (COMMIT_SHA, COMMIT_REF, etc.)
release: {
commit: process.env.COMMIT_SHA,
branch: process.env.COMMIT_REF,
version: '1.0.0',
environment: 'production',
},
// Aient auth (or set AIENT_PUBLISHABLE_KEY env var)
publishableKey: process.env.AIENT_PUBLISHABLE_KEY,
// Extract request context
attributesFromHeaders: {
'enduser.id': 'x-user-id',
'tenant.id': 'x-tenant-id',
'client.ip': 'x-forwarded-for',
},
// Sampling (10% in production)
traceSampler: 'parentbased_traceidratio',
// Error handling
captureUnhandledErrors: true,
exitOnUnhandledException: true,
flushTimeoutMs: 2000,
// Custom endpoint (alternative to OTEL_EXPORTER_OTLP_ENDPOINT env var)
exporterUrl: 'https://collector.example.com',
exporterHeaders: { 'x-api-key': 'your-key' },
// Debug logging (alternative to OTEL_LOG_LEVEL env var)
logLevel: 'DEBUG', // 'ALL' | 'VERBOSE' | 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' | 'NONE'
// Multi-backend fan-out (advanced - overrides exporterUrl)
// spanProcessors: [
// new BatchSpanProcessor(new OTLPHttpJsonTraceExporter({
// url: 'https://collector-a.example.com/v1/traces',
// })),
// new BatchSpanProcessor(new OTLPHttpJsonTraceExporter({
// url: 'https://collector-b.example.com/v1/traces',
// })),
// ],
})
}
# Set sampling ratio
OTEL_TRACES_SAMPLER_ARG=0.1
Environment Variables
Configure via env instead of code:
# Endpoints
OTEL_EXPORTER_OTLP_ENDPOINT=https://collector.example.com # Base URL
OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://traces.example.com/v1/traces
OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=https://logs.example.com/v1/logs
# Protocol
OTEL_EXPORTER_OTLP_TRACES_PROTOCOL=http/json
OTEL_EXPORTER_OTLP_LOGS_PROTOCOL=http/json
# Legacy http/protobuf values are accepted for compatibility but fall back to JSON.
# Headers
OTEL_EXPORTER_OTLP_HEADERS=x-api-key=secret,env=prod
# Sampling
OTEL_TRACES_SAMPLER=parentbased_traceidratio
OTEL_TRACES_SAMPLER_ARG=0.1
# Service
OTEL_SERVICE_NAME=my-service
OTEL_SDK_DISABLED=true # Kill switch
# Aient auth
AIENT_PUBLISHABLE_KEY=pk_xxx
OTLP JSON protocol contract
The SDK exports traces and logs as OTLP/HTTP JSON protobuf payloads with Content-Type: application/json.
The serializer follows the OTLP JSON mapping used by the OpenTelemetry protocol:
- request envelopes are
ExportTraceServiceRequestandExportLogsServiceRequestJSON objects (resourceSpansandresourceLogs); - JSON field names are lowerCamelCase, for example
startTimeUnixNanoanddroppedAttributesCount; - trace IDs and span IDs are hex strings, not base64;
- 64-bit timestamps and integer attribute values are decimal strings;
- enum fields such as span kind, span status, and log severity are encoded as numbers;
- arbitrary byte attributes are base64 strings;
- spans and logs are grouped by resource and instrumentation scope, including schema URLs when present.
@aient/otel does not bundle protobufjs, @opentelemetry/otlp-transformer, @opentelemetry/otlp-exporter-base, or @opentelemetry/exporter-trace-otlp-http. Protocol-sensitive serializer behavior is covered by test/otlp-json-serializer.test.ts, and dependency regressions are covered by test/package-contract.test.ts.
Build Metadata (required for source mapping)
Set commit info for Aient to map errors to code. Use either the release config option or environment variables:
Via config (recommended):
registerOTel({
serviceName: 'my-app',
release: {
commit: process.env.COMMIT_SHA,
branch: process.env.COMMIT_REF,
version: '1.0.0',
environment: 'production',
}
})
Via environment variables:
COMMIT_SHA=$(git rev-parse HEAD)
COMMIT_REF=$(git rev-parse --abbrev-ref HEAD)
BUILD_DATE=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
Also reads VERCEL_GIT_COMMIT_SHA, NEXT_PUBLIC_COMMIT_SHA, etc.
Manual Spans & Logs
import { trace } from '@opentelemetry/api'
import { logs, SeverityNumber } from '@opentelemetry/api-logs'
// Spans
const tracer = trace.getTracer('my-component')
const span = tracer.startSpan('operation')
span.setAttribute('key', 'value')
span.end()
// Logs
const logger = logs.getLogger('my-component')
logger.emit({
severityNumber: SeverityNumber.INFO,
body: 'User signed up',
attributes: { plan: 'pro' },
})
Recording external-service failures on the active span
When integrating with third-party systems (GitHub, Slack, Stripe, Linear, email providers, etc), prefer attaching the failure reason to the current active span so traces are self-explanatory.
import { recordExternalFailure, recordExternalFailureReason } from '@aient/otel'
// When you have an Error/exception:
try {
await doExternalCall()
} catch (e) {
recordExternalFailure({
system: 'github',
operation: 'listInstallationRepos',
error: e,
attributes: {
'aient.external.http.status_code': 404,
'aient.external.installation_id': 123,
},
})
throw e
}
// When you only have a protocol-level error string (no exception thrown):
recordExternalFailureReason({
system: 'slack',
operation: 'chat.postMessage',
reason: 'not_in_channel',
attributes: { 'aient.external.slack.channel': 'C123...' },
})
Notes:
- Both helpers set span status to ERROR, attach
aient.external.*attributes, and emit anexceptionevent. aient.external.organisation_idis diagnostic customer context. Authenticated source tenant and environment remain collector-owned resource attributes (aient.organisation.idandaient.environment.*).- Historical telemetry retains its original attribute keys; raw attribute inspection remains available.
recordExternalFailureReasondoes not synthesize an Error/stacktrace (to avoid misleading stacks).
Defaults
| Feature | Default |
|---|---|
| Trace exporter | http/json → https://ingest.aient.ai/v1/traces |
| Log exporter | http/json → https://ingest.aient.ai/v1/logs |
| Sampler | always_on |
| Propagators | W3C Trace Context + Baggage |
| Instrumentations | fetch, Node http/https |
| Error capture | uncaughtException, unhandledRejection → log + flush + exit |
| Request telemetry | stable HTTP attributes, redacted queries, one access log per inbound request |
Request telemetry
Every inbound request's outermost server span carries OpenTelemetry's stable HTTP
server attributes, also when the framework only emits legacy names (Next.js):
http.request.method, url.path, url.query, url.scheme, http.route,
http.response.status_code, server.address, server.port, client.address,
user_agent.original, http.request.header.referer, network.protocol.version,
http.response.body.size and error.type. Request-header attributes come from the
platform request context (Vercel) or from the HTTP server instrumentation.
Each request produces one log record (scope @aient/otel/http) with those
attributes, http.server.request.duration in seconds, and the span's trace and span
IDs. The message is <method> <route or path> <status>. Severity: ERROR for 5xx,
WARN for 4xx, otherwise INFO. The http.server.request.duration histogram is
recorded when you configure metricReaders. Outbound fetch spans get the stable
client attributes but no access log.
Query values of credential keys become REDACTED in url.query, url.full,
http.target, http.url, and referrer attributes (http.referer and
http.request.header.referer); keys and other values stay. The same referrer
policy applies to application log request context. Defaults: OpenTelemetry's
signature keys plus access_token, refresh_token, id_token, client_secret,
api_key, apikey, password and token.
registerOTel({
httpRequestTelemetry: {
sensitiveQueryParameters: ["sig", "token", "session"], // replaces the defaults
knownMethods: ["GET", "POST", "PURGE"], // or OTEL_INSTRUMENTATION_HTTP_KNOWN_METHODS
accessLogs: true, // default
},
})
Next.js on Vercel needs nothing more. For other Node servers (self-hosted Next.js,
Express, Fastify, NestJS, plain http), register the standard HTTP server
instrumentation so client address, user agent, referer and response size exist:
import { HttpInstrumentation } from "@opentelemetry/instrumentation-http";
registerOTel({
instrumentations: ["auto", new HttpInstrumentation({
headersToSpanAttributes: { server: { requestHeaders: ["referer"], responseHeaders: ["content-length"] } },
})],
});
License
MIT