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

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

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.

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:

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

@MessageHandler('my_app_command.create_user') // <-- Use this as the routing key
  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:

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

Wildcard Routing

If subscriberName uses a wildcard:

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

JetStream Example

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.

Last updated