Delving Developer

Efficiently Setting Up NATS in a NestJS Project

Eddie Cunningham
Eddie Cunningham
3 min readNestJS
Cover Image for Efficiently Setting Up NATS in a NestJS Project

Setting up NATS in a NestJS project can significantly improve communication between microservices, ensuring efficient and reliable message passing. This article will guide you through the process of setting up NATS in a NestJS project, covering prerequisites, installation, configuration, and implementation.

Prerequisiteslink

Before diving into the implementation, make sure you have the following:

  • Node.js installed on your system. NestJS requires Node.js version 10.13 or newer.
  • A NestJS project set up and ready to go. If you need help setting up a NestJS project, follow the official documentation.

Installationlink

To use NATS as a transport layer for your NestJS microservices, you need to install the @nestjs/microservices package. You can do so using the following command:

npm install @nestjs/microservices

This package provides the necessary modules and components to work with NATS and other message brokers.

Configurationlink

Now that you have installed the required package, it's time to configure NATS as the transport layer. In your NestJS project, open the main.ts file and make the following changes:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { Transport } from '@nestjs/microservices';

async function bootstrap() {
  const app = await NestFactory.createMicroservice(AppModule, {
    transport: Transport.NATS,
    options: {
      url: 'nats://localhost:4222',
    },
  });
  app.listen(() => console.log('Microservice is listening'));
}
bootstrap();

In this code snippet, we're importing Transport from the @nestjs/microservices package and configuring the application to use NATS as the transport layer. We also provide the url for the NATS server, which is typically nats://localhost:4222 for local development.

Implementationlink

With NATS configured, you can now implement message passing between microservices using NestJS. First, let's create a simple service that sends a message to a NATS topic:

// message.service.ts
import { Injectable } from '@nestjs/common';
import { ClientProxy, Transport, ClientProxyFactory } from '@nestjs/microservices';

@Injectable()
export class MessageService {
  private client: ClientProxy;

  constructor() {
    this.client = ClientProxyFactory.create({
      transport: Transport.NATS,
      options: {
        url: 'nats://localhost:4222',
      },
    });
  }

  async sendMessage(topic: string, data: any) {
    return this.client.send(topic, data).toPromise();
  }
}

This service creates a ClientProxy instance and exposes a sendMessage method that sends messages to a given NATS topic. The ClientProxyFactory.create() method is used to create the ClientProxy instance with the same NATS configuration as before.

Now, let's create a controller that uses the MessageService to send messages:

// app.controller.ts
import { Controller, Post, Body } from '@nestjs/common';
import { MessageService } from './message.service';

@Controller()
export class AppController {
  constructor(private readonly messageService: MessageService) {}

  @Post('send')
  async sendMessage(@Body() data: any) {
    return this.messageService.sendMessage('my-topic', data);
  }
}

This controller exposes a POST endpoint at /send that accepts a JSON payload and forwards it to the MessageService for sending to the NATS topic my-topic.

To receive messages from the NATS topic, create a new controller with a message pattern decorator:

// message.controller.ts
import { Controller } from '@nestjs/common';
import { MessagePattern } from '@nestjs/microservices';

@Controller()
export class MessageController {
  @MessagePattern('my-topic')
  handleMessage(data: any) {
    console.log('Received message:', data);
    return { response: 'Message received' };
  }
}

In this controller, we use the @MessagePattern() decorator to define a handler for the my-topic NATS topic. When a message is received on this topic, the handleMessage method is called, and the message data is logged to the console. The method then returns a response object containing a "Message received" message.

Now you have successfully set up NATS in your NestJS project, enabling seamless communication between microservices. By following this guide, you can continue to develop your application with efficient message passing, ensuring reliable and scalable communication across your services. Remember to adapt your NATS configuration to your specific needs and development environment. With this setup, your NestJS project will be well-equipped to handle the challenges of distributed systems and microservices architecture.