@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.
-
Automatic extraction and propagation of the
traceparent
header for HTTP and microservice requests. -
Async context management using Node.js
AsyncLocalStorage
for 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.
pnpm add @relab/nestjs-trace-context
# or
npm install @relab/nestjs-trace-context
Peer dependencies:
Make sure you have the following installed in your project:
@nestjs/common
@nestjs/core
@nestjs/microservices
amqplib
fastify
rxjs
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('*')
}
}
The configureTraceContext(app)
call (see above) automatically registers the TraceContextMicroserviceInterceptor
globally for your app, enabling trace context propagation for microservice handlers.
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 }
}
}
- 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.
MIT