> For the complete documentation index, see [llms.txt](https://docs.nestjstools.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.nestjstools.com/broker-integration/nats.md).

# Nats

## Messaging with NATS

### ⚙️ Installation

```bash
npm install @nestjstools/messaging @nestjstools/messaging-nats-extension 
```

or

```bash
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

```ts
import { Module } from '@nestjs/common';
import { MessagingModule } from '@nestjstools/messaging';
import { MessagingNatsExtensionModule, NatsChannelConfig } from '@nestjstools/messaging-nats-extension';

@Module({
  imports: [
    MessagingNatsExtensionModule,
    MessagingModule.forRoot({
      buses: [
        {
          name: 'nats-message.bus',
          channels: ['nats-message'],
        },
      ],
      channels: [
        new NatsChannelConfig({
          name: 'nats-message',
          enableConsumer: true,
          connectionUris: ['nats://localhost:4222'],
          subscriberName: 'nats-core',
        }),
      ],
      debug: true,
    }),
  ],
})
export class AppModule {}
```

***

### 🚀 JetStream Configuration

```ts
import { Module } from '@nestjs/common';
import { MessagingModule } from '@nestjstools/messaging';
import { MessagingNatsExtensionModule, NatsJetStreamChannelConfig } from '@nestjstools/messaging-nats-extension';

@Module({
  imports: [
    MessagingNatsExtensionModule,
    MessagingModule.forRoot({
      buses: [
        {
          name: 'nats-message.bus',
          channels: ['nats-channel-jetstream'],
        },
      ],
      channels: [
        new NatsJetStreamChannelConfig({
          name: 'nats-channel-jetstream',
          connectionUris: ['nats://localhost:4222'],
          enableConsumer: true,
          streamConfig: {
            streamName: 'event-steam',
            deliverSubjects: ['my_app_command.*'],
            autoUpdate: true,
          },
          consumerConfig: {
            durableName: 'nats-durable_name',
            subject: 'my_app_command.*',
            autoUpdate: true,
          },
        }),
      ],
      debug: true,
    }),
  ],
})
export class AppModule {}
```

***

### 📤 Dispatching Messages

Use a controller to send messages through the bus.

```ts
import { Controller, Get } from '@nestjs/common';
import { CreateUser } from './application/command/create-user';
import { IMessageBus, MessageBus, RoutingMessage } from '@nestjstools/messaging';

@Controller()
export class AppController {
  constructor(
    @MessageBus('nats-message.bus') private natsMessageBus: IMessageBus,
  ) {}

  @Get('/nats')
  createUser(): string {
    this.natsMessageBus.dispatch(
      new RoutingMessage(new CreateUser('John FROM Nats'), 'my_app_command.create_user'),
    );
    return 'Message sent';
  }
}
```

***

### 📥 Handling Messages

Create a handler that listens to a specific routing key:

```ts
import { CreateUser } from '../create-user';
import {
  IMessageHandler,
  MessageHandler,
} from '@nestjstools/messaging';

@MessageHandler('my_app_command.create_user')
export class CreateUserHandler implements IMessageHandler<CreateUser> {
  async handle(message: CreateUser): Promise<void> {
    console.log(message);
    // Your logic here
  }
}
```

***

### 🌐 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**

```ts
@MessageHandler('my_app_command.create_user') // <-- Use this as the routing key
```

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

```ts
subscriberName = 'order.created';
// Message will be sent to 'order.created'
```

#### Wildcard Routing

If `subscriberName` uses a wildcard:

```ts
subscriberName = 'order.*';
message.messageRoutingKey = 'order.created';
// Message will be sent to 'order.created'
```

**JetStream Example**

```ts
subject = 'order.*'; // from consumer
message.messageRoutingKey = 'order.created';
// The message will be published to 'order.created'
```

***

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


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.nestjstools.com/broker-integration/nats.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
