NestJS Project Guide

Complete instrumentation approach for NestJS APIs and microservices

Use this guide for NestJS backends where request lifecycle, dependency injection, and module boundaries must remain observable.

Architecture Scope

  • HTTP controllers and middleware chain.
  • Service/provider calls.
  • Outbound HTTP/DB/queue operations.

Setup

Initialize the Node SDK before the NestJS app starts listening:

src/main.ts
import { initNodeSDK } from "@obtrace/sdk-js/node";
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
 
const ob = initNodeSDK({
  apiKey: process.env.OBTRACE_API_KEY!,
  serviceName: "orders-api",
  env: process.env.NODE_ENV,
  serviceVersion: process.env.OBTRACE_SERVICE_VERSION,
});
 
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();

The Node SDK auto-instruments all inbound HTTP requests, outbound fetch() calls, and console output. No NestJS-specific middleware or interceptor is needed for basic telemetry.

For business-specific telemetry, use the SDK instance:

src/orders/orders.service.ts
import { ob } from "../main";
 
export class OrdersService {
  async create(dto: CreateOrderDto) {
    ob.log("info", "order.created", {
      attrs: { customer_id: dto.customerId, total: dto.total },
    });
    ob.metric("order.total", dto.total, "usd");
  }
}

Environment Variables

OBTRACE_API_KEY=obt_...
NODE_ENV=production
OBTRACE_SERVICE_VERSION=1.0.0

Validation Checklist

  • 4xx/5xx errors include trace context
  • All HTTP endpoints produce spans automatically
  • Console output appears as structured logs
  • Startup/shutdown hooks flush telemetry correctly

Production Hardening

  1. Call ob.shutdown() in the NestJS onApplicationShutdown lifecycle hook.
  2. Bound queue and retry configuration.
  3. Validate after module refactors.

Troubleshooting

  • No events after deploy: verify initNodeSDK runs before NestFactory.create.
  • Missing spans in async handlers: confirm context propagation.
  • High noise: reduce low-value event emission.

On this page