# NatsRecordSerializer

**Kind:** Class

**Source:** [`packages/microservices/serializers/nats-record.serializer.ts`](https://github.com/nestjs/nest/blob/master/packages/microservices/serializers/nats-record.serializer.ts#L10)

**Part of:** [Microservices](subsystem-packages-microservices)

`NatsRecordSerializer` converts outbound microservice packets into `NatsRecord` instances for NATS transport. It preserves an existing `NatsRecord` when provided and carries packet headers into the serialized record so NATS metadata is sent with the message.

**Implements:** `Serializer`

## Methods

| Method | Signature | Returns |
|---|---|---|
| `serialize` | `serialize(packet: any)` | `NatsRecord` |

## Diagram

```mermaid
graph LR
  A[Outbound packet] --> B[NatsRecordSerializer.serialize]
  B --> C{Packet data is NatsRecord?}
  C -->|Yes| D[Reuse NatsRecord]
  C -->|No| E[Build new NatsRecord]
  D --> F[Apply packet headers]
  E --> F
  F --> G[NATS publish/request transport]
```

## Usage

```ts
import { NatsRecordSerializer } from '@nestjs/microservices';

const serializer = new NatsRecordSerializer();

const record = serializer.serialize({
  pattern: 'orders.created',
  data: {
    orderId: 'order-123',
    status: 'created',
  },
  headers: {
    'x-correlation-id': 'request-456',
  },
});

// Pass the serialized record to the NATS transport layer.
console.log(record.data);
console.log(record.headers);
```

## AI Coding Instructions

- Use `NatsRecordSerializer` at the NATS transport boundary to convert outbound packet data into the NATS-specific record format.
- Preserve packet headers when constructing or modifying serialization flows; headers commonly carry correlation IDs, tracing context, and routing metadata.
- Do not unnecessarily wrap data that is already a `NatsRecord`; the serializer is designed to retain existing records.
- Keep application payloads transport-agnostic where possible, and add NATS-specific headers or record configuration only when integrating with the NATS client.

## Relationships

- IMPORTS → `loadPackage`
- IMPORTS → `isObject`
