nestrs-microservices provides message-based transport adapters for nestrs, analogous to @nestjs/microservices. It supports request-reply patterns (#[message_pattern]), fire-and-forget events (#[event_pattern]), and in-process pub/sub via EventBus. The HTTP and microservice servers can share a single process in hybrid mode.
Feature flags
Enable transports by adding the corresponding feature to yournestrs dependency:
| Feature | Transport |
|---|---|
microservices | TCP (default; always included when this group is enabled) |
microservices-nats | NATS |
microservices-redis | Redis Pub/Sub |
microservices-kafka | Apache Kafka |
microservices-mqtt | MQTT |
microservices-rabbitmq | RabbitMQ (AMQP) |
microservices-grpc | gRPC (tonic) |
Transport trait
The core async interface for all transport adapters. You use this indirectly through ClientProxy.
Transport options structs
Each transport has its own options type passed toNestFactory::create_microservice_*:
| Transport | Server options | Client options |
|---|---|---|
| TCP | TcpMicroserviceOptions | TcpTransportOptions |
| NATS | NatsMicroserviceOptions | NatsTransportOptions |
| Redis | RedisMicroserviceOptions | RedisTransportOptions |
| gRPC | GrpcMicroserviceOptions | GrpcTransportOptions |
| RabbitMQ | RabbitMqMicroserviceOptions | RabbitMqTransportOptions |
| Kafka | KafkaMicroserviceOptions | KafkaTransportOptions |
| MQTT | MqttMicroserviceOptions | MqttTransportOptions |
Message handlers
Declare message handlers in a#[micro_routes] impl block on a struct that is registered as a provider:
Cross-cutting on message handlers
Apply guards, interceptors, and pipes to individual message handlers using their microservice variants:| Attribute | Purpose |
|---|---|
#[use_micro_guards(G)] | Run before the handler; G implements MicroCanActivate |
#[use_micro_interceptors(I)] | Observe inbound patterns; I implements MicroIncomingInterceptor |
#[use_micro_pipes(P)] | Transform inbound JSON; P implements MicroPipeTransform |
MicroCanActivate trait
ClientProxy
A typed wrapper around a Transport for outgoing messages. Use send for request-reply and emit for fire-and-forget.
ClientsModule
Registers named ClientProxy instances and a ClientsService into a DynamicModule for import into any module.
ClientConfig is provided, ClientProxy itself is exported as a default client (no name lookup needed). With multiple configs, use ClientsService::expect(name).
ClientConfig
Builder for named transport clients:
ClientsService
Provides named ClientProxy lookup after ClientsModule::register has been imported.
EventBus
In-process pub/sub bus. Automatically registered when you use ClientsModule. Use EventBus::publish to emit events and #[on_event] inside #[event_routes] to subscribe.
Hybrid mode (HTTP + microservice)
Run both an HTTP server and a microservice transport in the same process:TransportError
The error type returned from message handlers and ClientProxy methods.