High-Performance Microservices with @hazeljs/grpc
Build gRPC servers in HazelJS with decorator-based RPC handlers. Type-safe, high-performance service-to-service communication with full DI integration.
Introduction
The @hazeljs/grpc package brings gRPC server support to HazelJS with a decorator-based API. Build high-performance, type-safe microservices using Protocol Buffers and HTTP/2—with full dependency injection and the familiar HazelJS module pattern.
Why gRPC with HazelJS?
Microservices often need efficient, type-safe communication. gRPC provides high-performance RPC over HTTP/2 with Protocol Buffers for serialization. The HazelJS gRPC module simplifies this with:
- Decorator-Based Handlers: Use
@GrpcMethod('ServiceName', 'MethodName')to declare RPC handlers—no manual wiring - Full DI Integration: Controllers are resolved from the HazelJS container—inject services, repositories, and other providers
- Proto Loading: Load
.protofiles at runtime with configurable options - Discovery Compatible: The Discovery package supports
protocol: 'grpc'for service registration
Installation
Install from npm:
npm install @hazeljs/grpcQuick Start
Define your service in a .proto file, create a controller with @GrpcMethod, and configure the module:
syntax = "proto3";
package hero;
service HeroService {
rpc FindOne (HeroById) returns (Hero);
}
message HeroById { int32 id = 1; }
message Hero { int32 id = 1; string name = 2; }import { Injectable, HazelModule } from '@hazeljs/core';
import { GrpcMethod, GrpcModule } from '@hazeljs/grpc';
import { join } from 'path';
@Injectable()
export class HeroGrpcController {
@GrpcMethod('HeroService', 'FindOne')
findOne(data: { id: number }) {
return { id: data.id, name: 'Hero' };
}
}
@HazelModule({
imports: [
GrpcModule.forRoot({
protoPath: join(__dirname, 'hero.proto'),
package: 'hero',
url: '0.0.0.0:50051',
}),
],
providers: [HeroGrpcController],
})
export class AppModule {}Bootstrap
Register handlers and start the gRPC server after your HTTP server:
import { HazelApp } from '@hazeljs/core';
import { GrpcModule, GrpcServer } from '@hazeljs/grpc';
import { Container } from '@hazeljs/core';
const app = new HazelApp(AppModule);
GrpcModule.registerHandlersFromProviders([HeroGrpcController]);
await app.listen(3000);
const grpcServer = Container.getInstance().resolve(GrpcServer);
await grpcServer.start();Configuration
Configure proto path, package name, bind URL, and loader options. Use forRootAsync when config depends on other services:
GrpcModule.forRoot({
protoPath: join(__dirname, 'hero.proto'),
package: 'hero',
url: '0.0.0.0:50051',
loader: { keepCase: true, longs: String, enums: String },
});Learn More
For full documentation, API reference, and best practices, see the gRPC Package documentation. Install from npm.