Nats
Messaging with NATS
βοΈ Installation
npm install @nestjstools/messaging @nestjstools/messaging-nats-extension or
yarn add @nestjstools/messaging @nestjstools/messaging-nats-extensionπ¦ Overview
This guide demonstrates how to integrate NATS (and NATS JetStream) into a NestJS application using @nestjstools/messaging and the messaging-nats-extension.
We cover:
Basic NATS setup
Using JetStream
Message dispatch and handling
Cross-language messaging
Routing strategies
Configuration options
βοΈ Basic NATS Configuration
π JetStream Configuration
π€ Dispatching Messages
Use a controller to send messages through the bus.
π₯ Handling Messages
Create a handler that listens to a specific routing key:
π Cross-Language Communication
To interact with NestJS handlers from external services (e.g., written in Go, Python, etc.):
Publish a message to the queue
Include the
messaging-routing-keyheader
Thatβs it! The NestJS app will route the message to the correct handler.
π§ Routing Strategy
Routing is determined by the subscriberName or deliverSubjects.
Static Routing
If subscriberName is a concrete subject:
Wildcard Routing
If subscriberName uses a wildcard:
JetStream Example
π NATS message options
The NATS extension provides two per-message option types, depending on whether you are using standard NATS or JetStream.
π‘ Standard NATS
For standard NATS channels, use NatsMessageOptions.
βοΈ Available options
π·οΈ
headersβ custom NATS headers represented asRecord<string, string>
βΉοΈ The
messaging-routing-keyheader is added automatically by the extension.
π NATS JetStream
For JetStream channels, use NatsJetStreamMessageOptions.
Available JetStream options
NatsJetStreamMessageOptions extends the standard NATS message options and additionally supports JetStream-specific publishing behavior.
π·οΈ
headersβ custom NATS headersβ³
ttlβ message time-to-liveπ
retriesβ number of publish retry attemptsβ±οΈ
timeoutβ publish timeout in millisecondsπ
scheduleβ JetStream scheduled-delivery value
TTL example
The message is configured with a 5-minute time-to-live.
Retry and timeout example
Publishing can be retried up to 3 times, with a 2-second publish timeout.
Scheduled delivery example
βοΈ Configuration Options
NatsChannelConfig
name
Name of the NATS channel (e.g., 'nats-message')
enableConsumer
Enable message consumption
connectionUris
NATS server URIs (e.g., ['nats://localhost:4222'])
subscriberName
Unique identifier for the subscriber
π Note: JetStream and NATS offer extensive configurations. If this setup doesn't suit your needs, you can fork and customize the base channel classes provided in this package.
Last updated
Was this helpful?