Skip to content

OpenTelemetry guide

OpenTelemetry for NestJS

NestJS sits on Express or Fastify, so the usual Node.js instrumentation works, plus a NestJS instrumentation that names spans after controllers and handlers.

3 min read9 sectionsUpdated

On this page

Key points

  • Start the SDK before NestJS is imported, in a separate file.
  • Add HTTP, Express (or Fastify) and NestJS core instrumentations.
  • Database drivers (pg, mysql2, ioredis) need their own instrumentations.
  • Node.js exports JSON directly to VitalRix.

Install

bash
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-nestjs-core @opentelemetry/instrumentation-pg

tracing.ts

tracing.tstypescript
// src/tracing.ts: must be loaded before anything imports @nestjs/*
import { NodeSDK } from '@opentelemetry/sdk-node';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';
import { resourceFromAttributes } from '@opentelemetry/resources';
import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
import { ExpressInstrumentation } from '@opentelemetry/instrumentation-express';
import { NestInstrumentation } from '@opentelemetry/instrumentation-nestjs-core';
import { PgInstrumentation } from '@opentelemetry/instrumentation-pg';

const exporter = new OTLPTraceExporter({
  url: `${process.env.VITALRIX_URL}/api/v1/traces/otlp/v1/traces`,
  headers: { 'x-api-key': process.env.VITALRIX_API_KEY ?? '' },
});

export const sdk = new NodeSDK({
  resource: resourceFromAttributes({
    'service.name': process.env.OTEL_SERVICE_NAME ?? 'accounts-api',
    'service.version': process.env.SERVICE_VERSION ?? '0.0.0',
    'deployment.environment.name': process.env.DEPLOYMENT_ENVIRONMENT ?? 'production',
  }),
  spanProcessors: [new BatchSpanProcessor(exporter)],
  instrumentations: [new HttpInstrumentation(), new ExpressInstrumentation(), new NestInstrumentation(), new PgInstrumentation()],
});
sdk.start();
process.once('SIGTERM', () => sdk.shutdown().finally(() => process.exit(0)));
main.tstypescript
// src/main.ts
import './tracing';                 // first import, before Nest
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();

Why import order matters

Instrumentation works by patching modules when they are first loaded. If @nestjs/core, express or pg are imported before the SDK starts, they are not patched and you get few or no spans. Importing ./tracing first (or running node -r ./dist/tracing.js dist/main.js) avoids that. For ES modules, use the --import flag with the instrumentation hook, as in the Node.js tracing guide.

Fastify adapter

If you use @nestjs/platform-fastify, replace the Express instrumentation with @opentelemetry/instrumentation-fastify (or the Fastify project's own OpenTelemetry plugin). The NestJS and HTTP instrumentations stay the same.

Check that it works

  1. Send a few requests to the app.
  2. In VitalRix, open APM: accounts-api appears in the service catalog within a minute, with request rate, error rate and p95.
  3. Open an endpoint and then one request to see its trace waterfall, including database spans.
  4. If nothing arrives, check the exporter's (or the Collector's) logs for export errors: 401 means the key or header is wrong, 402 that a new host is over the plan's APM host allowance. The packages have a check command that sends one test log.

Add service.version so new releases appear as deploy markers, and put the trace ID in your logs so each trace shows its log lines. See APM and logs, metrics and traces.

Frequently asked questions

Should I create spans with decorators?

You can write a small decorator that wraps methods in tracer.startActiveSpan. Keep custom spans for meaningful business steps, not every provider method.

How do I trace microservice transports?

HTTP and gRPC are covered by their instrumentations. For message brokers, use the broker client’s instrumentation, or inject and extract context in message headers.

  • OpenTelemetry for FastAPI: Trace a FastAPI service with OpenTelemetry: instrument the app, async database drivers and httpx, run uvicorn workers correctly and export.
  • OpenTelemetry for Go: Instrument a Go service with OpenTelemetry: set up the tracer provider, wrap net/http with otelhttp, pass context everywhere and export the spans.
  • OpenTelemetry for PHP and Laravel: Trace a Laravel app with OpenTelemetry: install the PHP extension and auto-instrumentation packages, configure PHP-FPM and trace queries.
  • OpenTelemetry for Flask: Instrument a Flask app with OpenTelemetry, in code or with zero code: trace routes, SQLAlchemy and outgoing calls, and export to VitalRix.
  • OpenTelemetry for Python: setup guide: Add OpenTelemetry to a Python service: install the distro, auto-instrument with opentelemetry-instrument, export to VitalRix and add custom spans.
  • OpenTelemetry for Ruby on Rails: Trace a Ruby on Rails app with OpenTelemetry: gems, an initializer with use_all, ActiveRecord and Sidekiq spans, Puma workers and exporting to VitalRix.

Watch your own site and services with VitalRix

Uptime checks, APM, logs, real-user monitoring, alerts and status pages in one place. Every product has a free tier and no credit card is needed.