![]() |
VOOZH | about |
NestJS is a progressive Node.js framework for building efficient, reliable, and scalable server-side applications. One of its powerful features is the microservices architecture, which allows developers to build distributed systems.
NestJS provides built-in transporters like TCP, Redis, and NATS, but sometimes you might need to create a custom transporter to meet specific requirements. This article explores how to create and use custom transporters in NestJS.
Transporters in NestJS are responsible for communication between microservices. They abstract the underlying communication protocol, allowing developers to focus on business logic. NestJS provides several built-in transporters, but custom transporters can be created to use different protocols or integrate with specific services.
The built-in transporters are:
While these built-in transporters cover a wide range of use cases, there are situations where a custom transporter is necessary. For example, integrating with a legacy system or a third-party service with a unique protocol might require a custom solution.
Creating a custom transporter might be necessary when:
To create a new NestJS project, you can use the NestJS CLI (@nestjs/cli). Install it globally using npm:
npm install -g @nestjs/cliCreating a New NestJS Project using the below command
nest new nest-gfg
cd nest-gfg
You will be prompted to choose a package manager. Select either npm or yarn according to your preference.
Step 3: Install Required Packages
Install the @nestjs/microservices package if it’s not already included:
npm install @nestjs/microservices
npm install @nestjs/platform-socket.io
npm install @nestjs/websockets
Step 4:Create the Custom Transporter
Create a new file custom.transporter.ts and app.gateway.ts in the src directory.
"dependencies": {
"@nestjs/common": "^10.0.0",
"@nestjs/core": "^10.0.0",
"@nestjs/microservices": "^10.3.10",
"@nestjs/platform-express": "^10.0.0",
"@nestjs/platform-socket.io": "^10.3.10",
"@nestjs/websockets": "^10.3.10",
"reflect-metadata": "^0.2.0",
"rxjs": "^7.8.1"
}
Example: Creating Custom Transporter
To start the application run the following command.
npm run start