Skip to main content

Data and monitoring · Intermediate · 25 min

Instrument a Node.js app with OpenTelemetry traces and metrics

By Padding · Updated 18 Nov 2026
Node.js 26.13.1 on node:26 · OpenTelemetry JS 3.1.1 (sdk-node 0.301.2) · Express 5.3.0 · OpenTelemetry Collector contrib 0.166.0

You will load the OpenTelemetry JS 3.1 SDK into an Express 5 app on Node.js 26, trace its requests and outgoing fetch calls, add your own span and histogram, send both over OTLP to a Collector, and stop the app without losing its last spans.

On this page

Logs tell you what one process said. When a checkout is slow, you want something else: the whole path of that one request, from the moment it reached your API, through every call it made to other services, with the time each part took. That record is a trace, and each timed part of it is a span. Alongside traces you usually want metrics, numbers that summarise many requests at once.

OpenTelemetry is the vendor-neutral standard for producing both. Your code talks to its API. An SDK collects what the API records and sends it in the OTLP format to an OpenTelemetry Collector, which forwards it to whatever backend you use: Jaeger, Grafana Tempo, Prometheus or a hosted service. Change the backend and the app code stays the same.

In this tutorial you build a small Express 5 shop API that prices a basket by calling a second service over fetch. You load the OpenTelemetry JS SDK before the app starts, so Express, the HTTP server and fetch produce spans without changes to their code. Then you add one span and one histogram of your own, watch both arrive in a Collector, and make sure the app flushes its last data when it stops. If traces, metrics and logs are new to you, read how metrics, logs and traces fit together first.

Step 1 · Create the project and install the packages

Make a throwaway folder and install Express with the OpenTelemetry packages. Every version is pinned with --save-exact, because the OpenTelemetry JS packages that start with 0. are still marked experimental and can change between minor releases:

Bash
mkdir -p ~/otel-shop-demo
cd ~/otel-shop-demo
npm init -y
npm pkg set type=commonjs
npm install --save-exact express@5.3.0 \
  @opentelemetry/api@1.10.0 \
  @opentelemetry/sdk-node@0.301.2 \
  @opentelemetry/sdk-metrics@3.1.1 \
  @opentelemetry/exporter-trace-otlp-proto@0.301.2 \
  @opentelemetry/exporter-metrics-otlp-proto@0.301.2 \
  @opentelemetry/auto-instrumentations-node@0.83.1

What each package does:

  • @opentelemetry/api is the small interface your own code calls to make spans and metrics. Libraries depend on it too. Without an SDK loaded, every call is a cheap no-op.
  • @opentelemetry/sdk-node is the SDK. It collects spans and metrics, batches them and hands them to exporters.
  • The two exporter-*-otlp-proto packages send traces and metrics over OTLP as protobuf on HTTP, port 4318.
  • @opentelemetry/sdk-metrics provides the reader that exports metrics on a timer.
  • @opentelemetry/auto-instrumentations-node bundles instrumentation for common modules, including http, Express and Node's built-in fetch.

The app is CommonJS (require) on purpose. Instrumentation works by patching modules as they load, and for CommonJS that needs no extra flags. If your own app is an ES module ("type": "module" or .mjs files), the start command also needs --experimental-loader=@opentelemetry/instrumentation/hook.mjs, or Express is not patched and you get no route spans.

Check it worked

Bash
node --version
npm ls @opentelemetry/sdk-node @opentelemetry/auto-instrumentations-node express

node --version prints v26. and a patch number. npm ls lists @opentelemetry/sdk-node@0.301.2, @opentelemetry/auto-instrumentations-node@0.83.1 and express@5.3.0, with no invalid or missing warnings.

Step 2 · Write a prices service and the shop API

The shop API needs something to call, so the trace has more than one service in it. Create prices.js, a tiny service with only Node's built-in http module. It returns a price list for one currency, and it prints the traceparent header of every request it receives. You will use that line later to follow one request across both services:

Bash
cat > prices.js <<'JS'
const http = require('node:http')

const PRICES = {
  NGN: { tea: 1500, bread: 1200, rice: 9000 },
  KES: { tea: 150, bread: 80, rice: 700 },
  GHS: { tea: 15, bread: 12, rice: 90 },
}

http
  .createServer((req, res) => {
    const url = new URL(req.url, 'http://localhost')
    console.log('traceparent', req.headers.traceparent ?? '(none)')
    const table = PRICES[url.searchParams.get('currency')]
    res.writeHead(table ? 200 : 404, { 'content-type': 'application/json' })
    res.end(JSON.stringify(table ?? { error: 'unknown currency' }))
  })
  .listen(4000, '127.0.0.1', () => console.log('prices listening on 4000'))
JS

Now the shop API. basket.js holds the pricing logic, so you can change it later without touching the routes:

Bash
cat > basket.js <<'JS'
const PRICES_URL = process.env.PRICES_URL ?? 'http://127.0.0.1:4000'

async function priceBasket(items, currency) {
  const url = `${PRICES_URL}/prices?currency=${encodeURIComponent(currency)}`
  const response = await fetch(url, { signal: AbortSignal.timeout(2000) })
  if (!response.ok) throw new Error(`prices service answered ${response.status}`)
  const prices = await response.json()

  let total = 0
  for (const item of items) {
    const price = prices[item.sku]
    if (price === undefined) {
      const err = new Error(`unknown sku ${item.sku}`)
      err.status = 422
      throw err
    }
    total += price * item.qty
  }
  return total
}

module.exports = { priceBasket }
JS

app.js has a health route and one POST /api/checkout route. It checks the input before it prices anything, and its error handler returns short JSON messages without a stack trace:

Bash
cat > app.js <<'JS'
const express = require('express')
const { priceBasket } = require('./basket')

const app = express()
app.disable('x-powered-by')
app.use(express.json({ limit: '10kb' }))

app.get('/api/health', (req, res) => {
  res.json({ status: 'ok' })
})

app.post('/api/checkout', async (req, res) => {
  const { items, currency } = req.body ?? {}
  const itemsOk =
    Array.isArray(items) &&
    items.length > 0 &&
    items.every((i) => typeof i?.sku === 'string' && Number.isInteger(i?.qty) && i.qty > 0 && i.qty <= 100)
  if (!itemsOk || typeof currency !== 'string' || !/^[A-Z]{3}$/.test(currency)) {
    return res.status(422).json({ error: 'send items [{sku, qty}] and a three-letter currency' })
  }
  const total = await priceBasket(items, currency)
  res.json({ currency, total })
})

app.use((err, req, res, next) => {
  const status = err.status ?? 500
  res.status(status).json({ error: status === 500 ? 'internal error' : err.message })
})

const port = Number(process.env.PORT ?? 3000)
app.listen(port, '127.0.0.1', () => console.log(`shop-api listening on ${port}`))
JS

Express 5 passes errors thrown inside async handlers to the error handler for you, so a failed fetch becomes a 500 with no extra code. Start the prices service in your second terminal and leave it running:

Bash
cd ~/otel-shop-demo
node prices.js

Check it worked

The second terminal prints prices listening on 4000. In your first terminal, check that the other two files parse and that the service answers:

Bash
node --check app.js && node --check basket.js && echo "syntax ok"
curl -s "http://127.0.0.1:4000/prices?currency=NGN"

You see syntax ok, then {"tea":1500,"bread":1200,"rice":9000}. The second terminal prints traceparent (none), because curl sends no trace header.

Step 3 · Run a Collector that prints what it receives

The SDK needs somewhere to send its data. In production that is a Collector next to your app, which batches, filters and forwards to your backend. Here the Collector has one job: receive OTLP over HTTP and print everything with its debug exporter, so you can read the raw spans and metrics.

Create otelcol.yaml:

Bash
cat > otelcol.yaml <<'YAML'
receivers:
  otlp:
    protocols:
      http:
        endpoint: 0.0.0.0:4318

exporters:
  debug:
    verbosity: detailed

service:
  pipelines:
    traces:
      receivers: [otlp]
      exporters: [debug]
    metrics:
      receivers: [otlp]
      exporters: [debug]
YAML

The receiver listens on all interfaces inside its own container, which it must do for Docker's port mapping to reach it. The -p 127.0.0.1:4318:4318 below publishes it on your machine's loopback address only, so nothing outside can send you data. Check the file, then start the Collector in the background. If your user is not in the docker group, put sudo in front of each docker command:

Bash
docker run --rm -v "$PWD/otelcol.yaml:/etc/otelcol-contrib/config.yaml:ro" \
  otel/opentelemetry-collector-contrib:0.166.0 validate --config /etc/otelcol-contrib/config.yaml
docker run -d --rm --name otelcol -p 127.0.0.1:4318:4318 \
  -v "$PWD/otelcol.yaml:/etc/otelcol-contrib/config.yaml:ro" \
  otel/opentelemetry-collector-contrib:0.166.0

validate prints nothing when the file is correct. A typo in a key name makes it print the error and exit before anything starts.

Check it worked

Bash
docker logs otelcol 2>&1 | grep "Everything is ready"

You see a line ending in Everything is ready. Begin running and processing data. If you see nothing, run docker logs otelcol without the grep to read the error.

Step 4 · Load the SDK before the app

The SDK has to start before Express, http or anything else you want traced is loaded. Instrumentation patches a module at the moment it is first required, and a module loaded earlier stays unpatched. So the SDK goes in its own file, and Node's --import flag runs that file before app.js.

Create telemetry.mjs:

Bash
cat > telemetry.mjs <<'JS'
import { NodeSDK } from '@opentelemetry/sdk-node'
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node'
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto'
import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-proto'
import { PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics'

const sdk = new NodeSDK({
  serviceName: 'shop-api',
  traceExporter: new OTLPTraceExporter(),
  metricReaders: [
    new PeriodicExportingMetricReader({
      exporter: new OTLPMetricExporter(),
      exportIntervalMillis: 15000,
    }),
  ],
  instrumentations: [getNodeAutoInstrumentations()],
})

sdk.start()

let stopping = false
async function stop(signal) {
  if (stopping) return
  stopping = true
  try {
    await sdk.shutdown()
    console.log(`telemetry flushed after ${signal}`)
  } catch (err) {
    console.error('telemetry shutdown failed', err)
  } finally {
    process.exit(0)
  }
}

process.on('SIGINT', () => stop('SIGINT'))
process.on('SIGTERM', () => stop('SIGTERM'))
JS

What this sets up:

  • serviceName becomes the service.name resource attribute on everything the app sends. Backends group data by it, so give every service its own name.
  • The exporters have no URL in the code. They read OTEL_EXPORTER_OTLP_ENDPOINT and default to http://localhost:4318, the Collector you just started. If your backend needs an API key, set it in OTEL_EXPORTER_OTLP_HEADERS from your process manager's environment file, never in the source.
  • Spans are batched and sent every few seconds. Metrics are sent every 15 seconds here; the default is 60.
  • The signal handlers are the subject of a later step. Leave them in place.

Start the app in your third terminal. The first command limits the auto-instrumentation to the three modules this app uses, which keeps the output readable and start-up quick:

Bash
cd ~/otel-shop-demo
export OTEL_NODE_ENABLED_INSTRUMENTATIONS=http,express,undici
node --import ./telemetry.mjs app.js

It prints shop-api listening on 3000. undici is the instrumentation that covers Node's built-in fetch. Back in your first terminal, check out a basket:

Bash
curl -s -X POST http://127.0.0.1:3000/api/checkout \
  -H 'content-type: application/json' \
  -d '{"currency":"NGN","items":[{"sku":"tea","qty":2},{"sku":"rice","qty":1}]}'

The answer is {"currency":"NGN","total":12000}.

Check it worked

Wait about five seconds for the batch to go out, then list the span names the Collector printed:

Bash
docker logs otelcol 2>&1 | grep -E 'Name +:|Kind +:|http.route'

You see several spans from one request, something like:

  • a Server span named after the route, such as POST /api/checkout, with http.route: Str(/api/checkout);
  • Internal spans from Express for the middleware and the route handler;
  • a Client span for the fetch to port 4000.

Run docker logs otelcol on its own to see each span in full, including service.name: Str(shop-api) under the resource attributes, and the Trace ID that every span of the request shares.

Step 5 · Follow the request into the prices service

Look at the second terminal. The line from your checkout now reads something like traceparent 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01. The undici instrumentation added that header to the outgoing fetch. It is the W3C Trace Context format: a version, the 32-character trace ID, the ID of the calling span, and a flags field where 01 means sampled.

If the prices service were instrumented too, its SDK would read the header and make its spans children of that fetch span, and your backend would show both services in one trace. That is all distributed tracing needs: each service passes the header on.

Check it worked

Copy the 32-character trace ID from the second terminal (the part between the first and second hyphen) and search for it in the Collector's output. Replace the example ID with yours:

Bash
docker logs otelcol 2>&1 | grep -c "4bf92f3577b34da6a3ce929d0e0e4736"

The count is 3 or more, one line for each span of that request. The same ID in both places proves the context crossed from one service to the other.

Step 6 · Add your own span and a histogram

Automatic spans show the HTTP layer. They cannot say which basket was priced or how big it was. Add that with the API package: a span around the pricing work, with attributes, and a histogram that records how many items each basket had. Replace basket.js:

Bash
cat > basket.js <<'JS'
const { trace, metrics, SpanStatusCode } = require('@opentelemetry/api')

const tracer = trace.getTracer('shop-api')
const meter = metrics.getMeter('shop-api')
const basketSize = meter.createHistogram('checkout.basket.size', {
  description: 'Number of items in each priced basket',
  unit: '{item}',
  advice: { explicitBucketBoundaries: [1, 2, 5, 10, 20, 50] },
})

const PRICES_URL = process.env.PRICES_URL ?? 'http://127.0.0.1:4000'

async function priceBasket(items, currency) {
  return tracer.startActiveSpan('price-basket', async (span) => {
    try {
      span.setAttribute('shop.currency', currency)
      const url = `${PRICES_URL}/prices?currency=${encodeURIComponent(currency)}`
      const response = await fetch(url, { signal: AbortSignal.timeout(2000) })
      if (!response.ok) throw new Error(`prices service answered ${response.status}`)
      const prices = await response.json()

      let total = 0
      let count = 0
      for (const item of items) {
        const price = prices[item.sku]
        if (price === undefined) {
          const err = new Error(`unknown sku ${item.sku}`)
          err.status = 422
          throw err
        }
        total += price * item.qty
        count += item.qty
      }

      span.setAttribute('shop.item_count', count)
      basketSize.record(count, { 'shop.currency': currency })
      return total
    } catch (err) {
      span.recordException(err)
      span.setStatus({ code: SpanStatusCode.ERROR, message: err.message })
      throw err
    } finally {
      span.end()
    }
  })
}

module.exports = { priceBasket }
JS

Points worth knowing:

  • startActiveSpan makes price-basket the current span while the callback runs. The fetch inside it becomes its child, so the trace shows the price lookup nested inside your business step.
  • Every span must be ended, and the finally block makes sure it is, even on an error. A span that never ends is never exported.
  • On failure the span records the exception as an event and is marked as an error, so error traces are easy to find.
  • Metric attributes become dimensions. shop.currency has a handful of values, which is fine. Never put user IDs, emails or free text in metric attributes: each distinct value is a new series your backend stores and may bill you for.
  • advice suggests histogram bucket edges suited to item counts. Without it you get the default edges, which are tuned for milliseconds.

Restart the app: press Ctrl+C in the third terminal, then run the same start command again:

Bash
node --import ./telemetry.mjs app.js

Send one good basket and one with a product the prices service does not have:

Bash
curl -s -X POST http://127.0.0.1:3000/api/checkout \
  -H 'content-type: application/json' \
  -d '{"currency":"NGN","items":[{"sku":"bread","qty":3},{"sku":"tea","qty":1}]}'
echo
curl -s -X POST http://127.0.0.1:3000/api/checkout \
  -H 'content-type: application/json' \
  -d '{"currency":"GHS","items":[{"sku":"milk","qty":1}]}'
echo

The first answers {"currency":"NGN","total":5100}. The second answers {"error":"unknown sku milk"} with status 422.

Check it worked

Wait 15 seconds so the metrics export runs, then look for your span and your histogram:

Bash
docker logs otelcol 2>&1 | grep -E 'price-basket|shop\.|Status code|checkout.basket.size'

You see two price-basket spans. The NGN one carries shop.currency: Str(NGN) and shop.item_count: Int(4). The GHS one has Status code : Error, the message unknown sku milk and an exception event. Further down, a metric block shows Name: checkout.basket.size, Unit: {item} and DataType: Histogram, with a count of 1 for NGN and the bucket edges you chose. The failed basket recorded nothing, because record runs only after pricing succeeds.

Step 7 · Stop the app without losing the last spans

The SDK holds spans in memory for a few seconds and metrics for up to 15, then sends them in batches. That saves network calls, but it means a process that exits straight away drops whatever is still waiting. Deploys and restarts happen all the time, so without a clean shutdown the requests just before each restart vanish from your traces.

sdk.shutdown() exports everything still buffered and then closes the exporters. The handlers in telemetry.mjs call it on SIGINT (Ctrl+C) and SIGTERM (what Docker, Kubernetes and systemd send to stop a process), then exit. Registering a handler replaces Node's default exit on those signals, which is why the code calls process.exit itself. In a larger app, also close the HTTP server first so requests in flight can finish.

To see it work, send a basket in a new currency and stop the app straight away, well inside the batch delay. Run the curl command, then press Ctrl+C in the third terminal within a second or two:

Bash
curl -s -X POST http://127.0.0.1:3000/api/checkout \
  -H 'content-type: application/json' \
  -d '{"currency":"KES","items":[{"sku":"rice","qty":2}]}'
echo

The answer is {"currency":"KES","total":1400}, and the third terminal prints telemetry flushed after SIGINT as the app exits.

Check it worked

Bash
docker logs otelcol 2>&1 | grep -E 'shop.currency: Str\(KES\)'

You see shop.currency: Str(KES) at least twice: once on the price-basket span and once on the histogram data point. Both were still in memory when you pressed Ctrl+C and reached the Collector only because of the shutdown call. Comment out the two process.on lines, repeat the test with GHS and a known product, and the span usually never arrives, because the process exits before the batch is sent.

On a slow or metered link, such as a server on prepaid mobile data, telemetry is traffic you pay for. Keep the batching, and in busy services sample traces rather than sending all of them: OTEL_TRACES_SAMPLER=parentbased_traceidratio with OTEL_TRACES_SAMPLER_ARG=0.1 keeps about one trace in ten.

Step 8 · Clean up

Stop the prices service with Ctrl+C in the second terminal. Stop the Collector, which also removes its container because it was started with --rm, and delete the demo folder:

Bash
docker stop otelcol
Bash
cd ~
rm -rf ~/otel-shop-demo

To remove the Collector image as well, run docker image rm otel/opentelemetry-collector-contrib:0.166.0.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.