For the complete documentation index, see llms.txt. This page is also available as Markdown.

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.):

  1. Publish a message to the queue

  2. Include the messaging-routing-key header

  1. 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 as Record<string, string>

ℹ️ The messaging-routing-key header 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

Property
Description

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?