@relab/nestjs-trace-context
v3.7.0
Published
Implementation trace context for Nest.js
Readme
@relab/nestjs-trace-context
Purpose
@relab/nestjs-trace-context provides seamless propagation and management of the W3C Trace Context (traceparent header) in NestJS applications, supporting both HTTP (Fastify) and microservices (RabbitMQ via amqplib).
It enables distributed tracing by ensuring that trace context is available throughout your request lifecycle, making it easy to correlate logs and traces across services.
Features
- Automatic extraction and propagation of the
traceparentheader for HTTP and microservice requests. - Async context management using Node.js
AsyncLocalStoragefor safe trace context access throughout the request. - NestJS Middleware for HTTP servers (Fastify).
- NestJS Interceptor for microservices (RabbitMQ).
- Simple API to access the current trace context anywhere in your application.
Installation
pnpm add @relab/nestjs-trace-context
# or
npm install @relab/nestjs-trace-contextPeer dependencies:
Make sure you have the following installed in your project:
@nestjs/common@nestjs/core@nestjs/microservicesamqplibfastifyrxjs
Usage
1. HTTP (Fastify) Setup
main.ts
import { configureTraceContext } from '@relab/nestjs-trace-context'
const app = /* create nestjs app */
configureTraceContext(app)app.module.ts
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common'
import { TraceContextModule, TraceContextMiddleware } from '@relab/nestjs-trace-context'
@Module({
imports: [TraceContextModule],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(TraceContextMiddleware).forRoutes('*')
}
}2. Microservices (RabbitMQ) Setup
The configureTraceContext(app) call (see above) automatically registers the TraceContextMicroserviceInterceptor globally for your app, enabling trace context propagation for microservice handlers.
Accessing Trace Context
Anywhere in your application, inject TraceContextService to access the current trace context:
import { TraceContextService } from '@relab/nestjs-trace-context'
@Injectable()
export class MyService {
constructor(private readonly traceContext: TraceContextService) {}
myMethod() {
const trace = this.traceContext.getContext()
// trace: { traceId, spanId, traceFlags }
}
}API
- TraceContextModule: Import into your root module.
- TraceContextMiddleware: Apply as middleware for HTTP requests.
- TraceContextMicroserviceInterceptor: Automatically applied for microservices via
configureTraceContext. - TraceContextService: Inject to access or set the current trace context.
License
MIT
