A payload codec for transforming data before storage and after retrieval in a Key-Value store.
Purpose
The KvPayloadCodec handles the transformation of values between the application layer and
the storage layer in the NATS Key-Value store. All values in NATS KV are ultimately stored
as binary data (Uint8Array), and this codec provides a way to customize how data is
encoded/decoded.
Data Flow
When storing: Application data (string or Uint8Array) → encode() → Uint8Array (stored in NATS)
When retrieving: Uint8Array (from NATS) → decode() → Uint8Array (returned to application)
Important Notes
The codec always returns Uint8Array, but KvEntry provides convenience methods (string(), json())
for parsing the binary data into other formats
Even when the input is a string, the codec must convert it to and work with Uint8Array
The decode method must always return a Uint8Array, even if your application uses string values
Custom codecs can implement compression, encryption, or other transformations
Example Use Cases
Compression: Reduce the size of stored data
Encryption: Secure sensitive data at rest
Example
// Simple compression codec using a hypothetical compression library constCompressionCodec = (): KvPayloadCodec=> { return { encode(v: Payload): Uint8Array { // Convert string to Uint8Array if needed constdata = typeofv === "string" ? newTextEncoder().encode(v) : v; // Apply compression returncompressData(data); }, decode(d: Uint8Array): Uint8Array { // Decompress the data returndecompressData(d); } }; };
A payload codec for transforming data before storage and after retrieval in a Key-Value store.
Purpose
The KvPayloadCodec handles the transformation of values between the application layer and the storage layer in the NATS Key-Value store. All values in NATS KV are ultimately stored as binary data (Uint8Array), and this codec provides a way to customize how data is encoded/decoded.
Data Flow
Important Notes
Example Use Cases
Example