Skip to content

NatsContext

reference
1 min readUpdated

Kind: Class

Source: packages/microservices/ctx-host/nats.context.ts

Part of: Microservices

NatsContext provides access to NATS-specific metadata for an incoming microservice message. Use it in NATS message handlers to inspect the message subject and any associated headers without coupling application logic directly to the transport layer.

Extends: BaseRpcContext

Methods

MethodSignatureReturns
getSubjectgetSubject()void
getHeadersgetHeaders()void

Diagram

mermaid
graph LR
  Publisher[NATS Publisher] -->|subject + headers + payload| Server[NATS Server]
  Server --> Handler[Message Handler]
  Handler --> Context[NatsContext]
  Context --> Subject[getSubject()]
  Context --> Headers[getHeaders()]

Usage

ts
import { Controller } from '@nestjs/common';
import { Ctx, MessagePattern, Payload } from '@nestjs/microservices';
import { NatsContext } from '@nestjs/microservices';

@Controller()
export class OrdersController {
  @MessagePattern('orders.created')
  handleOrderCreated(
    @Payload() order: { id: string },
    @Ctx() context: NatsContext,
  ) {
    const subject = context.getSubject();
    const headers = context.getHeaders();

    console.log(`Received order ${order.id} on ${subject}`);
    console.log('Request headers:', headers);

    return { received: true };
  }
}

AI Coding Instructions

  • Inject NatsContext with @Ctx() only in handlers executed through the NATS transport.
  • Use getSubject() when behavior depends on the NATS subject that routed the message.
  • Use getHeaders() for transport metadata such as tracing, correlation IDs, or custom message attributes.
  • Do not assume headers are always present; handle missing or undefined header values safely.
  • Keep business logic transport-agnostic where possible, and isolate NATS-specific metadata handling at the message-handler boundary.

Used by

1 reference from 1 file. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example.

Imported by (1)

  • NatsControllerintegration/microservices/src/nats/nats.controller.ts:19

Was this page helpful?

Download as PDF
NatsContext — NestJS head-to-head