0
0
NestJSframework~30 mins

Microservice transports in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Microservice transports
📖 Scenario: You are building a simple microservice system with NestJS. An API gateway receives HTTP requests and forwards them to a user microservice via TCP transport. The user microservice handles the business logic and returns results.
🎯 Goal: Set up a NestJS microservice with TCP transport, create message handlers, and connect a client from the API gateway to communicate with the microservice.
📋 What You'll Learn
Create a TCP microservice that listens on port 3001
Define a message handler using @MessagePattern
Register a ClientProxy in the API gateway module
Send messages from the gateway controller to the microservice
💡 Why This Matters
🌍 Real World
Microservice transports are the backbone of distributed NestJS applications, enabling services to communicate reliably across different deployment environments.
💼 Career
Understanding transport layers is essential for backend developers building scalable microservice architectures with NestJS.
Progress0 / 4 steps
1
Create the TCP microservice
In the user microservice's main.ts, create a NestJS microservice using Transport.TCP listening on host 0.0.0.0 and port 3001.
NestJS
Need a hint?

Use NestFactory.createMicroservice(AppModule, { transport: Transport.TCP, options: { host: '0.0.0.0', port: 3001 } }).

2
Create a message handler
In the user microservice controller, create a method getUser decorated with @MessagePattern({ cmd: 'get_user' }) that receives a data object with an id property and returns a user object with id and name.
NestJS
Need a hint?

Use @MessagePattern({ cmd: 'get_user' }) above your handler method.

3
Register ClientProxy in gateway module
In the API gateway's module, register a ClientsModule with a TCP client named USER_SERVICE that connects to the user microservice on localhost:3001.
NestJS
Need a hint?

Use ClientsModule.register([{ name: 'USER_SERVICE', transport: Transport.TCP, options: { host: 'localhost', port: 3001 } }]).

4
Send messages from gateway controller
In the gateway controller, inject the USER_SERVICE client using @Inject('USER_SERVICE') and create a GET endpoint /users/:id that sends a get_user message to the microservice with the user ID.
NestJS
Need a hint?

Inject with @Inject('USER_SERVICE') private client: ClientProxy and send with this.client.send({ cmd: 'get_user' }, { id }).