> For the complete documentation index, see [llms.txt](https://docs.nestjstools.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.nestjstools.com/components/middlewares.md).

# 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

```ts
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:

```ts
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. |


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.nestjstools.com/components/middlewares.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
