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


⚙️ 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