Middlewares
π§΅ Middlewares
In @nestjstools/messaging
Middlewares are functions or classes that act on messages before they reach their respective handlers. They are ideal for adding logging, validation, authentication, transformation, or metrics collection to your messaging flow.
Each channel has its own middleware stack, and the middlewares are executed in order, just like an HTTP middleware pipeline.
π What Does a Middleware Do?
A middleware has access to:
The incoming message (
RoutingMessage
)The execution context
The ability to:
Modify the message
Stop message processing
Forward the message to the next middleware or the final handler
β¨ Use Cases
Logging message flow
Validating payloads
Injecting metadata or tracing headers
Authenticating messages
Handling common errors or retries
π οΈ Creating a Middleware
Define a class that implements the Middleware
interface and use the @MessagingMiddleware()
decorator.
Example: Logging Middleware
π Important: Always call
context.next().process(...)
to continue down the middleware chain.
π Attaching Middleware to a Channel
Middlewares are assigned per channel in your MessagingModule config:
βοΈ Middleware Pipeline
When a message is dispatched to a channel:
It passes through the middleware stack, in the order theyβre defined.
Each middleware can:
Modify the message
Stop further processing
Pass the message on via
context.next().process(...)
The final destination is the message handler.
Benefits
π Reusable Logic
Write once, apply to multiple channels
π§Ό Separation of Concerns
Keep logging/validation out of core handler logic
π Security & Validation
Centralize authentication and schema checks
π Customizable
Easily extend for metrics, tracing, throttling, etc.
Last updated