@nats-io/kv
    Preparing search index...

    Type Alias KvPayloadCodec

    A payload codec for transforming data before storage and after retrieval in a Key-Value store.

    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.

    1. When storing: Application data (string or Uint8Array) → encode() → Uint8Array (stored in NATS)
    2. When retrieving: Uint8Array (from NATS) → decode() → Uint8Array (returned to application)
    • 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
    • Compression: Reduce the size of stored data
    • Encryption: Secure sensitive data at rest
    // Simple compression codec using a hypothetical compression library
    const CompressionCodec = (): KvPayloadCodec => {
    return {
    encode(v: Payload): Uint8Array {
    // Convert string to Uint8Array if needed
    const data = typeof v === "string" ? new TextEncoder().encode(v) : v;
    // Apply compression
    return compressData(data);
    },
    decode(d: Uint8Array): Uint8Array {
    // Decompress the data
    return decompressData(d);
    }
    };
    };
    type KvPayloadCodec = {
        decode(d: Uint8Array): Uint8Array;
        encode(v: Payload): Uint8Array;
    }
    Index

    Methods

    Methods

    • Parameters

      • d: Uint8Array

      Returns Uint8Array

    • Parameters

      • v: Payload

      Returns Uint8Array