Nestjstools Messaging Docs
  • Introduction
    • What is this library?
    • Supported message brokers
  • Getting Started
    • Installation
    • Initialize Module
    • Message Handler
    • Disaptch a message
  • Components
    • Message Handlers
    • Normalizers
    • Exception Listeners
    • Middlewares
    • Message Bus
    • Channel
  • Broker integration
    • RabbitMQ
    • Redis
    • Google PubSub
    • Amazon SQS
    • Nats
  • Best practice
    • CQRS based on RabbitMQ
    • Create wrapper class for Message Bus
    • Consumer as the background process
Powered by GitBook
On this page
  • 🧡 Middlewares
  • πŸ” What Does a Middleware Do?
  • ✨ Use Cases
  • πŸ› οΈ Creating a Middleware
  • πŸ”Œ Attaching Middleware to a Channel
  • βš™οΈ Middleware Pipeline
  • Benefits
Export as PDF
  1. Components

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

import { Injectable } from '@nestjs/common';
import { Middleware, MessagingMiddleware, RoutingMessage, MiddlewareContext } from '@nestjstools/messaging';

@Injectable()
@MessagingMiddleware()
export class TestMiddleware implements Middleware {
  async process(message: RoutingMessage, context: MiddlewareContext): Promise<MiddlewareContext> {
    console.log('!!!! WORKS');
    
    // Continue processing the pipeline
    return await context.next().process(message, context);
  }
}

πŸ” 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:

import { MessagingModule, InMemoryChannelConfig, AmqpChannelConfig, ExchangeType } from '@nestjstools/messaging';
import { TestMiddleware } from './middlewares/test.middleware';

@Module({
  imports: [
    MessagingModule.forRoot({
      buses: [
        {
          name: 'message.bus',
          channels: ['my-channel'],
        },
      ],
      channels: [
        new InMemoryChannelConfig({
          name: 'my-channel',
          middlewares: [TestMiddleware],
        }),
      ],
      debug: true,
    }),
  ],
})
export class AppModule {}

βš™οΈ Middleware Pipeline

When a message is dispatched to a channel:

  1. It passes through the middleware stack, in the order they’re defined.

  2. Each middleware can:

    • Modify the message

    • Stop further processing

    • Pass the message on via context.next().process(...)

  3. The final destination is the message handler.


Benefits

Feature
Description

πŸ”„ 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.

PreviousException ListenersNextMessage Bus

Last updated 9 days ago