Logs tell you what happened inside one process. Traces tell you what happened to one request as it crossed your whole system. With OpenTelemetry you can add them to a Node.js service in about fifteen minutes, without locking yourself into any vendor.

What you will build

An Express service that sends a trace for every request, including:

  • the incoming HTTP request with its route and status;
  • every PostgreSQL query it runs;
  • every outgoing fetch call, linked to the next service's trace.

1. Install the packages

npm install @opentelemetry/api @opentelemetry/sdk-node @opentelemetry/sdk-trace-base \
  @opentelemetry/exporter-trace-otlp-http @opentelemetry/resources \
  @opentelemetry/instrumentation-http @opentelemetry/instrumentation-express \
  @opentelemetry/instrumentation-pg @opentelemetry/instrumentation-undici

The instrumentation-* packages patch common libraries automatically, so you do not have to change your route handlers.

2. Create instrumentation.mjs

import { register } from 'node:module';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { ExpressInstrumentation } from '@opentelemetry/instrumentation-express';
import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
import { PgInstrumentation } from '@opentelemetry/instrumentation-pg';
import { UndiciInstrumentation } from '@opentelemetry/instrumentation-undici';
import { resourceFromAttributes } from '@opentelemetry/resources';
import { NodeSDK } from '@opentelemetry/sdk-node';
import { BatchSpanProcessor, ParentBasedSampler, TraceIdRatioBasedSampler } from '@opentelemetry/sdk-trace-base';

// Needed for ES module apps so libraries can be patched as they load.
register('@opentelemetry/instrumentation/hook.mjs', import.meta.url);

const sdk = new NodeSDK({
  resource: resourceFromAttributes({
    'service.name': process.env.OTEL_SERVICE_NAME ?? 'checkout-api',
    'service.version': process.env.SERVICE_VERSION ?? '0.0.0',
    'deployment.environment.name': process.env.DEPLOYMENT_ENVIRONMENT ?? 'production',
  }),
  sampler: new ParentBasedSampler({ root: new TraceIdRatioBasedSampler(1) }),
  spanProcessors: [new BatchSpanProcessor(new OTLPTraceExporter({
    url: process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT,
    headers: { 'x-api-key': process.env.TRACES_API_KEY },
  }))],
  instrumentations: [new HttpInstrumentation(), new ExpressInstrumentation(), new PgInstrumentation(), new UndiciInstrumentation()],
});
sdk.start();
process.once('SIGTERM', () => sdk.shutdown().finally(() => process.exit(0)));

Three attributes matter most:

  • service.name groups everything from this service.
  • service.version lets you compare releases; a new version is a deployment marker.
  • deployment.environment.name keeps production and staging apart.

3. Load it before your app

Instrumentation must run before Express and pg are imported:

node --import ./instrumentation.mjs server.js

For CommonJS apps, use node --require with a CommonJS version of the file instead.

4. Point the exporter at your backend

OTEL_SERVICE_NAME=checkout-api
SERVICE_VERSION=$(git rev-parse --short HEAD)
DEPLOYMENT_ENVIRONMENT=production
OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://api.vitalrix.com/api/v1/traces/otlp/v1/traces
TRACES_API_KEY=pk_your_key

Keep the key in server-side environment variables only, never in browser code.

5. How traces cross services

When your service calls another one with fetch, the instrumentation adds a traceparent header. If the next service is also instrumented, its spans join the same trace. That is what turns separate logs into one timeline from the browser to the database.

The parent-based sampler keeps whole traces together: if the first service samples a request, every service downstream samples it too.

6. Verify

  1. Start the app and make a few requests.
  2. Open your tracing tool and find checkout-api.
  3. Open a trace: you should see the HTTP span, the Express route, and a child span for every SQL query.

If nothing arrives, check the exporter URL and key first, then make sure the instrumentation file really loads before the app.

7. Add your own spans where it helps

Automatic instrumentation covers I/O. For expensive in-process work, add a span:

import { trace } from '@opentelemetry/api';
const tracer = trace.getTracer('checkout');

await tracer.startActiveSpan('calculate-shipping', async (span) => {
  try { return await calculateShipping(cart); } finally { span.end(); }
});

Common pitfalls

  • Instrumentation loaded too late: Express routes are missing. Load the file with --import.
  • Secrets in spans: do not put tokens or personal data into span attributes. Good backends also strip common secrets before storage.
  • Sampling too aggressively: with low traffic, keep the ratio at 1 (every request). Lower it only when volume is high.

VitalRix accepts this exact setup and turns the traces into latency percentiles, error issues, slow queries and a service map. The full guide is in the APM setup docs.

Next.js and other frameworks

Next.js has built-in OpenTelemetry support: create an instrumentation.ts file at the project root that registers the SDK when process.env.NEXT_RUNTIME === 'nodejs', and Next.js creates spans for routes and server rendering itself. NestJS, Fastify and Koa work with the same setup as Express; add their instrumentation packages where available.

Linking logs to traces

Add the active trace id to your log lines so you can jump from a trace to its logs:

import { trace } from '@opentelemetry/api';
const traceId = trace.getActiveSpan()?.spanContext().traceId;
logger.info({ traceId, orderId }, 'Order created');

See structured logging for the full pattern.

Running in containers and Kubernetes

  • Pass the configuration as environment variables in your deployment, with the API key from a secret.
  • Add the version: SERVICE_VERSION from your image tag, so every rollout becomes a deployment marker.
  • With many services, run an OpenTelemetry Collector as a deployment or sidecar. Services send to the Collector, which batches, retries and forwards. It also lets you change the backend without redeploying services.

What to look at first

Once traces arrive, start with three views: the slowest endpoints by p95 (why percentiles), the endpoints with the most errors, and the database statements that take the most total time. Those three usually point to the biggest improvements.

Does OpenTelemetry slow down Node.js?

The overhead is small for most apps: spans are batched and exported in the background. On very busy services you can sample a share of requests.

Do I need the OpenTelemetry Collector?

Not for a single service. The SDK can export directly. A Collector helps when you have many services or want to send data to several backends.

Why are my Express routes missing from traces?

Usually the instrumentation loads after Express. Start Node with --import ./instrumentation.mjs so it runs first.

Try VitalRix free

Uptime monitoring, APM, logs, real user monitoring and status pages in one place. No credit card needed.