> 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/normalizers.md).

# Normalizers

## 🧪 Normalizers

### What is a Normalizer?

A **Normalizer** is a component that transforms messages between different formats before sending and after receiving. It plays a crucial role in serialization and deserialization—ensuring that messages are properly encoded for transmission and correctly decoded when received.

This is especially helpful when integrating with systems that require specific data formats like **Protobuf**, **Base64**, or **custom JSON structures**.

***

### 🧩 Why Use a Normalizer?

You may want to use a custom normalizer to:

* Work with **binary formats** like Protobuf
* Encode messages in **Base64** or another custom format
* Encrypt/decrypt messages
* Support **custom serialization logic** not handled by default JSON

***

### ⚙️ Defining a Normalizer

To create a normalizer, implement the `MessageNormalizer` interface and decorate the class with `@MessagingNormalizer()`.

#### Example: Base64 Normalizer

```ts
import { Injectable } from '@nestjs/common';
import { MessagingNormalizer, MessageNormalizer } from '@nestjstools/messaging';
import { Buffer } from 'buffer';

@Injectable()
@MessagingNormalizer()
export class Base64Normalizer implements MessageNormalizer {
  denormalize(message: string | object, type: string): Promise<object> {
    if (typeof message === 'object') {
      throw new Error('Message must be a string!');
    }
    return Promise.resolve(
      JSON.parse(Buffer.from(message, 'base64').toString('utf-8')),
    );
  }

  normalize(message: object, type: string): Promise<string> {
    const jsonString = JSON.stringify(message);
    return Promise.resolve(
      Buffer.from(jsonString, 'utf-8').toString('base64'),
    );
  }
}
```

***

### 🔄 How It Works

| Phase           | Description                                                                                   |
| --------------- | --------------------------------------------------------------------------------------------- |
| **Normalize**   | Called before sending. Converts a message object into a transport-safe string (e.g., Base64). |
| **Denormalize** | Called after receiving. Converts the raw string back into a message object.                   |

***

### 🎯 Usage Per Channel

You can assign a normalizer **per channel** in your messaging configuration. This allows different channels to use different formats as needed:

```ts
new InMemoryChannelConfig({
  name: 'my-channel',
  normalizer: Base64Normalizer, // Use custom normalizer for this channel
}),
```

> 💡 Each channel can use a different normalizer depending on the protocol or service it interacts with.

***

### Summary

| Feature            | Description                                              |
| ------------------ | -------------------------------------------------------- |
| `normalize()`      | Transforms message before it’s sent                      |
| `denormalize()`    | Parses message after it’s received                       |
| Per-channel config | Apply specific format handling per communication channel |


---

# 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/normalizers.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.
