Skip to content

ClientNats

reference
1 min readUpdated

Kind: Class

Source: packages/microservices/client/client-nats.ts

Part of: Microservices

ClientNats is a NATS-backed client responsible for establishing and managing a connection to a NATS broker. It initializes serialization, publishes messages and events, manages subscriptions/status updates, and exposes access to the underlying NATS client through unwrap().

Extends: ClientProxy

Methods

MethodSignatureReturns
closeclose()void
connectconnect()Promise<any>
createClientcreateClient()Promise<Client>
handleStatusUpdateshandleStatusUpdates(client: Client)void
onon(event: EventKey, callback: EventCallback)void
unwrapunwrap()T
createSubscriptionHandlercreateSubscriptionHandler(packet: ReadPacket & PacketId, callback: (packet: WritePacket) => any)void
publishpublish(partialPacket: ReadPacket, callback: (packet: WritePacket) => any)() => void
dispatchEventdispatchEvent(packet: ReadPacket)Promise<any>
initializeSerializerinitializeSerializer(options: NatsOptions['options'])void
initializeDeserializerinitializeDeserializer(options: NatsOptions['options'])void
mergeHeadersmergeHeaders(requestHeaders: THeaders)void

Properties

PropertyType
loggerany
natsClient`Client
connectionPromise`Promise
statusEventEmitterany

Where it refuses work

  • ClientNats stops the work with Error when !this.natsClient — “Not initialized. Please call the "connect" method first.”.
  • ClientNats stops the work with an early return when this.connectionPromise.
  • ClientNats stops the work with an early return when error.
  • ClientNats stops the work with an early return when rawPacket?.length === 0.
  • ClientNats stops the work with an early return when message.id && message.id !== packet.id.
  • ClientNats stops the work with an early return when isDisposed || err.

When something fails

  • ClientNats handles failure in 2 places: it logs it and continues in 1, and turns it into a return value in 1.

Diagram

mermaid
graph LR
  App[Application Code] --> ClientNats[ClientNats]
  ClientNats --> Serializer[Serializer Initialization]
  ClientNats --> Connection[createClient / connect]
  Connection --> NATS[NATS Broker]
  ClientNats --> Publish[publish / dispatchEvent]
  ClientNats --> Subscribe[createSubscriptionHandler / on]
  Connection --> Status[handleStatusUpdates]
  ClientNats --> RawClient[unwrap]

Usage

ts
import { ClientNats } from './client-nats';

const client = new ClientNats({
  servers: ['nats://localhost:4222'],
});

async function start() {
  await client.connect();

  // Register a handler for messages received on a subject.
  client.on('orders.created', async (message) => {
    console.log('Received order event:', message);
  });

  // Dispatch an event to NATS.
  await client.dispatchEvent('orders.created', {
    orderId: 'order-123',
    customerId: 'customer-456',
  });

  // Access the underlying NATS client when lower-level APIs are needed.
  const natsClient = client.unwrap();
  console.log('Connected to NATS:', !!natsClient);
}

start().catch(console.error);

// Close the connection during application shutdown.
// await client.close();

AI Coding Instructions

  • Call connect() before publishing events, registering subscriptions, or accessing the underlying client with unwrap().
  • Keep message payloads compatible with the configured serializer; initialize or preserve serializer behavior when extending the client.
  • Use dispatchEvent() for event-oriented publishing instead of bypassing the client with raw NATS calls unless lower-level functionality is required.
  • Ensure close() is called during application shutdown to release subscriptions and NATS connection resources.
  • Preserve status-update handling when changing connection logic so reconnects and broker state changes remain observable.

Relationships

  • IMPORTS → Logger
  • IMPORTS → loadPackage
  • IMPORTS → isObject

Was this page helpful?

Download as PDF
ClientNats — NestJS head-to-head