0
0
NestjsHow-ToBeginner ยท 4 min read

How to Use Microservices in NestJS: Simple Guide

In NestJS, you use microservices by creating separate microservice instances with ClientsModule and MicroserviceOptions. You connect services using transport layers like TCP or Redis, and communicate via messages or events using ClientProxy and message patterns.
๐Ÿ“

Syntax

To use microservices in NestJS, you define a microservice client with ClientsModule.register() and specify the transport type. Then, you create a microservice server using NestFactory.createMicroservice() with transport options. Communication happens through message patterns and ClientProxy.

  • ClientsModule.register(): Registers microservice clients with transport and options.
  • Transport: Defines the communication method (e.g., TCP, Redis).
  • createMicroservice(): Creates a microservice server instance.
  • ClientProxy: Used to send messages to microservices.
  • @MessagePattern(): Decorator to handle incoming messages in microservice.
typescript
import { Module } from '@nestjs/common';
import { ClientsModule, Transport } from '@nestjs/microservices';

@Module({
  imports: [
    ClientsModule.register([
      {
        name: 'SERVICE_NAME',
        transport: Transport.TCP,
        options: { host: 'localhost', port: 3001 },
      },
    ]),
  ],
})
export class AppModule {}

// Microservice server setup
import { NestFactory } from '@nestjs/core';
import { MicroserviceOptions, Transport } from '@nestjs/microservices';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {
    transport: Transport.TCP,
    options: { host: 'localhost', port: 3001 },
  });
  await app.listen();
}
bootstrap();
๐Ÿ’ป

Example

This example shows a simple NestJS microservice using TCP transport. The microservice listens for a message pattern { cmd: 'sum' } and returns the sum of two numbers. The client sends a message and logs the response.

typescript
import { Controller } from '@nestjs/common';
import { MessagePattern } from '@nestjs/microservices';

@Controller()
export class MathController {
  @MessagePattern({ cmd: 'sum' })
  sum(data: number[]): number {
    return data.reduce((a, b) => a + b, 0);
  }
}

// Microservice bootstrap
import { NestFactory } from '@nestjs/core';
import { MicroserviceOptions, Transport } from '@nestjs/microservices';
import { Module } from '@nestjs/common';

@Module({
  controllers: [MathController],
})
export class AppModule {}

async function bootstrap() {
  const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {
    transport: Transport.TCP,
    options: { port: 4000 },
  });
  await app.listen();
}
bootstrap();

// Client example
import { ClientProxyFactory, Transport } from '@nestjs/microservices';

async function client() {
  const client = ClientProxyFactory.create({
    transport: Transport.TCP,
    options: { port: 4000 },
  });

  const result = await client.send<number, number[]>({ cmd: 'sum' }, [1, 2, 3, 4]).toPromise();
  console.log('Sum result:', result);
}
client();
Output
Sum result: 10
โš ๏ธ

Common Pitfalls

Common mistakes when using microservices in NestJS include:

  • Not matching the @MessagePattern pattern exactly between client and server.
  • Forgetting to start the microservice with app.listen().
  • Using incorrect transport options or ports causing connection failures.
  • Not handling asynchronous responses properly with toPromise() or lastValueFrom().

Always ensure client and server use the same transport and options.

typescript
/* Wrong: Pattern mismatch */
@MessagePattern({ cmd: 'add' })
sum(data: number[]) { return data.reduce((a,b) => a+b, 0); }

// Client sends with different pattern
client.send({ cmd: 'sum' }, [1,2]); // No response

/* Right: Matching pattern */
@MessagePattern({ cmd: 'sum' })
sum(data: number[]) { return data.reduce((a,b) => a+b, 0); }

client.send({ cmd: 'sum' }, [1,2]); // Works correctly
๐Ÿ“Š

Quick Reference

  • Transport options: TCP, Redis, NATS, MQTT, GRPC
  • ClientProxy methods: send() for request-response, emit() for events
  • Message handlers: Use @MessagePattern() to listen for messages
  • Start microservice: Use NestFactory.createMicroservice() and app.listen()
โœ…

Key Takeaways

Use ClientsModule and NestFactory.createMicroservice to set up microservices in NestJS.
Match message patterns exactly between client and microservice handlers.
Choose the right transport layer like TCP or Redis for communication.
Use ClientProxy's send() method for request-response messaging.
Always start the microservice with app.listen() to accept messages.