Node.js instrumentation
Instrument a Node.js application with OpenTelemetry and send traces, logs, and metrics to Maple.
This guide sets up the OpenTelemetry Node.js SDK so your application sends traces, logs and metrics to Maple, with automatic instrumentation for HTTP servers, frameworks and database clients.
To have a coding agent do this setup, use the maple-onboard skill. To check an existing setup, use maple-audit.
Prerequisites
- Node.js 22.22.3+, 24.11.1+ or 26+ (the versions whose
module.registerHookscan run the ES module hook) - An ingest key from Settings → Ingestion in Maple. Use the private key (
maple_sk_…) for server applications.
Install
npm install @opentelemetry/api \
@opentelemetry/sdk-node \
@opentelemetry/auto-instrumentations-node \
@opentelemetry/instrumentation \
import-in-the-middle \
@opentelemetry/resources \
@opentelemetry/sdk-logs \
@opentelemetry/sdk-metrics \
@opentelemetry/exporter-trace-otlp-proto \
@opentelemetry/exporter-logs-otlp-proto \
@opentelemetry/exporter-metrics-otlp-protopnpm add @opentelemetry/api \
@opentelemetry/sdk-node \
@opentelemetry/auto-instrumentations-node \
@opentelemetry/instrumentation \
import-in-the-middle \
@opentelemetry/resources \
@opentelemetry/sdk-logs \
@opentelemetry/sdk-metrics \
@opentelemetry/exporter-trace-otlp-proto \
@opentelemetry/exporter-logs-otlp-proto \
@opentelemetry/exporter-metrics-otlp-protobun add @opentelemetry/api \
@opentelemetry/sdk-node \
@opentelemetry/auto-instrumentations-node \
@opentelemetry/instrumentation \
import-in-the-middle \
@opentelemetry/resources \
@opentelemetry/sdk-logs \
@opentelemetry/sdk-metrics \
@opentelemetry/exporter-trace-otlp-proto \
@opentelemetry/exporter-logs-otlp-proto \
@opentelemetry/exporter-metrics-otlp-protoConfigure
Create tracing.mjs next to your entry point. It starts the SDK before any of your application code loads.
// tracing.mjs
import { register } from "import-in-the-middle/register-hooks.mjs"
import { NodeSDK } from "@opentelemetry/sdk-node"
import { getNodeAutoInstrumentations } from "@opentelemetry/auto-instrumentations-node"
import { resourceFromAttributes } from "@opentelemetry/resources"
import { BatchLogRecordProcessor } from "@opentelemetry/sdk-logs"
import { PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics"
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto"
import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-proto"
import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-proto"
// Lets the instrumentations patch ES modules. CommonJS apps can drop this line.
register()
// OTEL_EXPORTER_OTLP_ENDPOINT switches to Maple Local (http://127.0.0.1:4318) without a code change.
const MAPLE_ENDPOINT = (process.env.OTEL_EXPORTER_OTLP_ENDPOINT || "https://ingest.maple.dev").replace(/\/$/, "") // EU: https://ingest.eu.maple.dev
const MAPLE_KEY = "YOUR_INGEST_KEY"
const headers = { authorization: `Bearer ${MAPLE_KEY}` }
const sdk = new NodeSDK({
resource: resourceFromAttributes({
"service.name": "my-node-app",
"deployment.environment.name": process.env.NODE_ENV || "development",
"vcs.repository.url.full": "https://github.com/acme/my-node-app",
"vcs.ref.head.revision": process.env.GITHUB_SHA ?? process.env.GIT_COMMIT,
}),
traceExporter: new OTLPTraceExporter({ url: `${MAPLE_ENDPOINT}/v1/traces`, headers }),
logRecordProcessors: [
new BatchLogRecordProcessor({
exporter: new OTLPLogExporter({ url: `${MAPLE_ENDPOINT}/v1/logs`, headers }),
}),
],
metricReaders: [
new PeriodicExportingMetricReader({
exporter: new OTLPMetricExporter({ url: `${MAPLE_ENDPOINT}/v1/metrics`, headers }),
}),
],
instrumentations: [getNodeAutoInstrumentations()],
})
sdk.start()
process.on("SIGTERM", () => {
sdk.shutdown().finally(() => process.exit(0))
})
BatchLogRecordProcessor takes { exporter } in @opentelemetry/sdk-logs 0.220.0 and later, including 3.x. Older releases take the exporter as the first argument, new BatchLogRecordProcessor(. A current release accepts the exporter as a positional argument without throwing, but then exports no log records.
On a Node.js version outside those in Prerequisites, import register from node:module instead and call register(. Node.js 26 marks that form as deprecated.
The example puts the key in source and uses the cloud endpoint unless OTEL_EXPORTER_OTLP_ENDPOINT is set, which is how you point it at Maple Local. An ingest key can only write telemetry to your organization. It cannot read data or call the Maple API. Keeping it in source means the SDK always starts with a complete configuration, so a deploy that is missing an environment variable cannot silently turn telemetry off. That is fine for a private repository. In a public repository, keep the key out of source with environment variables or a secret store.
Load the file before your application:
node --import ./tracing.mjs app.js
For a TypeScript entry point run through tsx, load tsx first:
node --import tsx --import ./tracing.mjs app.ts
Environment variables
The SDK can take its whole configuration from the standard OpenTelemetry variables. With them set, you do not need tracing.mjs: the register entry point of the auto-instrumentations package starts the SDK and reads the variables.
export OTEL_SERVICE_NAME="my-node-app"
export OTEL_EXPORTER_OTLP_ENDPOINT="https://ingest.maple.dev"
export OTEL_EXPORTER_OTLP_PROTOCOL="http/protobuf"
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer%20YOUR_INGEST_KEY"
export OTEL_TRACES_EXPORTER="otlp"
export OTEL_METRICS_EXPORTER="otlp"
export OTEL_LOGS_EXPORTER="otlp"
export OTEL_RESOURCE_ATTRIBUTES="deployment.environment.name=production,vcs.repository.url.full=https://github.com/acme/my-node-app"
node --require @opentelemetry/auto-instrumentations-node/register app.js
For an ES module app, also load a hooks.mjs with --import ./hooks.mjs so the instrumentations can patch ES modules:
// hooks.mjs
import { register } from "import-in-the-middle/register-hooks.mjs"
register()
OTEL_EXPORTER_OTLP_ENDPOINT takes the base URL. The exporters append /v1/traces, /v1/logs and /v1/metrics themselves. In OTEL_EXPORTER_OTLP_HEADERS the space after Bearer is written %20, because the specification URL-decodes header values.
Auto-instrumentation
getNodeAutoInstrumentations() enables the OpenTelemetry instrumentations for common libraries, including http, Express, Fastify, pg, mysql2, ioredis and many more. Each incoming request becomes a server span, and each outgoing HTTP call or database query becomes a child span.
To turn off instrumentations you do not want:
instrumentations: [
getNodeAutoInstrumentations({
"@opentelemetry/instrumentation-fs": { enabled: false },
"@opentelemetry/instrumentation-dns": { enabled: false },
}),
],
Custom spans
Wrap your own operations in spans:
import { trace, SpanStatusCode } from "@opentelemetry/api"
const tracer = trace.getTracer("my-app")
async function processOrder(orderId: string) {
return tracer.startActiveSpan("process-order", async (span) => {
try {
span.setAttribute("order.id", orderId)
span.setAttribute("payment.method", "card")
return await chargePayment(orderId)
} catch (error) {
span.recordException(error as Error)
span.setStatus({ code: SpanStatusCode.ERROR, message: (error as Error).message })
throw error
} finally {
span.end()
}
})
}
Service map edges come from instrumented client spans that propagate traceparent to an instrumented callee, not from attributes such as peer.service. See Service map.
Attributes Maple uses
Most attributes are optional. These unlock specific features.
Commits and GitHub
Set vcs.ref.head.revision (the full 40-character commit SHA) and vcs.repository.url.full on the resource. vcs.ref.head.revision drives deploy markers and the Recent deploys panel on each service page. With the GitHub integration, the two attributes also drive commit hover cards on traces. The resource in Configure already sets both. Read the SHA from your CI or host at build time, such as GITHUB_SHA or VERCEL_GIT_COMMIT_SHA, not from git at runtime:
export OTEL_RESOURCE_ATTRIBUTES="vcs.repository.url.full=https://github.com/acme/api,vcs.ref.head.revision=$GITHUB_SHA"
Databases
Database instrumentation sets the db.* attributes for you. For a driver without instrumentation, set them on a Client span:
import { SpanKind } from "@opentelemetry/api"
const user = await tracer.startActiveSpan(
"SELECT users",
{
kind: SpanKind.CLIENT,
attributes: {
"db.system.name": "postgresql",
"db.namespace": "app",
"db.query.text": "SELECT * FROM users WHERE id = $1",
},
},
async (span) => {
try {
return await client.query("SELECT * FROM users WHERE id = $1", [id])
} finally {
span.end()
}
},
)
db.system.name and db.namespace draw the database node on the service map. db.query.text groups statements into query shapes, so record it with placeholders, not bound values. See Database queries for the full list.
Log correlation
Log records emitted through the OpenTelemetry log SDK during an active span carry its trace and span IDs, so Maple links each log line to its trace.
The auto-instrumentations include pino, winston and bunyan instrumentations that add the active trace context to each log record. Pino and bunyan records are also sent through the log exporter configured above. Winston needs the @opentelemetry/ package for that.
Frameworks
Express and Fastify
No extra setup. getNodeAutoInstrumentations() includes the Express and Fastify instrumentations, so each request becomes a server span named after the method and route, with spans for middleware and handlers under it. Load tracing.mjs with --import so it runs before express or fastify is imported.
Hono
On Node.js, Hono runs on @hono/node-server, and the http instrumentation already creates a server span per request. To name spans after Hono’s routes, add the @hono/otel middleware:
npm install @hono/otelpnpm add @hono/otelbun add @hono/otelimport { Hono } from "hono"
import { httpInstrumentationMiddleware } from "@hono/otel"
const app = new Hono()
app.use(
httpInstrumentationMiddleware({
serviceName: "my-node-app",
// url.full holds the whole URL by default, query string included. Drop it so tokens in it are not exported.
getUrlFull: (c) => {
const url = new URL(c.req.url)
return `${url.origin}${url.pathname}`
},
}),
)
The middleware starts its own server span named after the matched route, alongside the one the http instrumentation creates. To get one server span per request, turn off incoming request spans in tracing.mjs and keep outgoing ones:
instrumentations: [
getNodeAutoInstrumentations({
"@opentelemetry/instrumentation-http": { disableIncomingRequestInstrumentation: true },
}),
],
This turns off incoming request spans for the whole process. If the same process runs another HTTP server that does not go through Hono, its requests lose their server spans; in that case keep the http instrumentation on and skip Hono’s middleware, or use ignoreIncomingRequestHook to skip only the Hono server’s requests.
The middleware uses the SDK that tracing.mjs started. For Hono on Cloudflare Workers, see Cloudflare Workers.
NestJS
getNodeAutoInstrumentations() includes the NestJS instrumentation, which adds spans for controllers and handlers under the HTTP server span. Load the tracing file before the compiled entry point:
node --import ./tracing.mjs dist/main.js
Bun
NodeSDK, the OTLP exporters and custom spans through @opentelemetry/api work under Bun. Load the file with bun -, and remove the register() call: Bun has no module.registerHooks and treats module.register as a no-op, so ES module imports are not patched. Automatic instrumentation is therefore unreliable, and Bun.serve requests get no server span. Use framework middleware such as @hono/otel for request spans, and check which library spans arrive before you rely on them.
Deno
Deno has OpenTelemetry built in, so you do not need the Node SDK. Start your app with OTEL_DENO=true and the standard variables from Environment variables. Deno traces Deno.serve requests and outgoing fetch calls, records HTTP server metrics, and exports console output as logs linked to the active span. Spans you create with npm:@opentelemetry/api go to the same exporter. See the Deno OpenTelemetry docs.
Next.js and Effect
- Next.js has its own guide: Next.js instrumentation.
- For Effect applications, use the Effect SDK.
Sampling
The SDK records every trace by default. To keep a share of new traces, set the standard sampler variables:
export OTEL_TRACES_SAMPLER="parentbased_traceidratio"
export OTEL_TRACES_SAMPLER_ARG="0.1" # keep 10% of new traces
parentbased_traceidratio follows the decision of the caller for requests that arrive with a traceparent, so a trace is kept or dropped as a whole across services. Maple can only weight sampled spans back up to the traffic you served when the sample rate reaches it, as a th value in tracestate or a SampleRate span attribute. Read Sampling and throughput before you turn sampling on.
Shutdown and flush
The SDK exports in batches, so a process that stops without shutting the SDK down loses its last batch. The SIGTERM handler in Configure calls sdk.shutdown(), which flushes traces, logs and metrics before the process exits. For a script or job that exits on its own, await sdk.shutdown() before it returns.
Verify
- Start your application and send it a few requests.
- In Maple, open Explore → Traces. The SDK sends spans in batches every 5 seconds by default, and metrics every 60 seconds.
- Each request should show up as one trace with a single root server span, named after the method and route (for example
GET /api/orders), and child spans for the queries and outgoing calls it made.
Your service also appears on the Services page once its first spans arrive.
Troubleshooting
401responses. The key is wrong, was copied from the other region, or the header is malformed. The header must beAuthorization: Bearer YOUR_. InINGEST_ KEY OTEL_EXPORTER_OTLP_HEADERSit is writtenAuthorization=Bearer%20YOUR_. See Ingest API status codes.INGEST_ KEY - Wrong path or port. Maple accepts OTLP over HTTP and gRPC on port 443. The
-protoand-httpexporters are the usual choice; the-grpcones also work with the base URL and no port. HTTP endpoints set in code need the full signal path (/v1/traces);OTEL_EXPORTER_OTLP_ENDPOINTtakes only the base URL. - Network. From the machine running the app, run
curl -i https://ingest.maple.dev/. Any HTTP status code means the host can reach Maple. A timeout or DNS error means a firewall or proxy is blocking outbound HTTPS.v1/ traces -X POST - Nothing exported.
tracing.mjsmust load before the modules it instruments, so use--importrather than importing it from your app. A process that exits right away can lose its last batch; callsdk.shutdown()before exit, as theSIGTERMhandler above does. SetOTEL_LOG_LEVEL=debugto print export errors to the console.
Running Express? The OpenTelemetry for Express guide covers load order, ESM and middleware span noise.