Building Type-Safe Microservices with NestJS and gRPC
Introduction
JSON over HTTP (REST) is great for public APIs, but for internal microservice-to-microservice communication, it's bloated and slow. gRPC (Google Remote Procedure Call) combined with Protocol Buffers (Protobuf) offers a compact, binary, and strictly typed alternative. NestJS makes adopting gRPC incredibly simple.
Why gRPC?
- Performance: Binary data is significantly smaller than text-based JSON.
- Streaming: Native support for bi-directional streaming (great for large datasets or real-time feeds).
- Contracts: The .proto file serves as the single source of truth. Both the client and server know exactly what data to expect.
Implementing in NestJS
1. Defining the Proto
Create a hero.proto file. This is language-agnostic.
1syntax = "proto3"; 2 3package hero; 4 5service HeroService { 6 rpc FindOne (HeroById) returns (Hero); 7} 8 9message HeroById { 10 int32 id = 1; 11} 12 13message Hero { 14 int32 id = 1; 15 string name = 2; 16}
2. The Microservice (Server)
In your NestJS controller, replace @Get() with @GrpcMethod().
1@Controller() 2export class HeroController { 3 @GrpcMethod('HeroService', 'FindOne') 4 findOne(data: HeroById): Hero { 5 return { id: 1, name: 'Superman' }; 6 } 7}
3. The Client
NestJS provides a simplistic client to consume this service.
1@Client({ 2 transport: Transport.GRPC, 3 options: { 4 package: 'hero', 5 protoPath: join(__dirname, 'hero.proto'), 6 }, 7}) 8client: ClientGrpc; 9 10onModuleInit() { 11 this.heroService = this.client.getService<HeroService>('HeroService'); 12}
The TypeScript Advantage
By using tools like ts-proto, you can auto-generate TypeScript interfaces from your .proto files. This means if you change a field in the Protobuf definition, your compiler will immediately yell at you in both the Client and Server code. This end-to-end type safety eliminates a massive class of runtime errors.
Conclusion
Combining the architecture of NestJS with the performance of gRPC creates a backend infrastructure that is robust, fast, and maintainable. It is the standard for modern distributed systems in 2026.




