@relab/nestjs-trace-context
TypeScript icon, indicating that this package has built-in type declarations

3.6.0 • Public • Published

@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 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.

Installation

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

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

Readme

Keywords

Package Sidebar

Install

npm i @relab/nestjs-trace-context

Weekly Downloads

187

Version

3.6.0

License

MIT

Unpacked Size

17.6 kB

Total Files

7

Last publish

Collaborators

  • relab