Skip to main content

Overview

Codecs provide bidirectional transformation between two representations of data. They combine input validation, output validation, and reversible transformations.

Basic Codec

Create a codec using z.codec() with two schemas and transformation functions:

Codec Structure

A codec is defined with:
  • Input Schema (A): Validates the encoded form
  • Output Schema (B): Validates the decoded form
  • decode: Transforms AB (forward direction)
  • encode: Transforms BA (backward direction)

Codec Operations

Decode (Forward)

Transform from input to output representation:

Encode (Backward)

Transform from output back to input representation:

Async Operations

All codec operations support async transformations:

Round-Trip Conversion

Codecs guarantee bidirectional transformation:

Codec Type Signatures

The type system ensures correct transformations:

Codecs with Refinements

Add refinements to codec schemas:

Complex Codec Example

Nested object with codec property:

Validation at Multiple Levels

Codecs validate at each level:

Mutating Refinements

Codecs support refinements that mutate data:

Codec with Overwrites

Apply transformations after codec operations:

Instance Checks

Error Handling

Best Practices

  1. Ensure reversibility - Encoding after decoding should return the original value
  2. Validate both directions - Both input and output schemas should have proper validation
  3. Use refinements for constraints - Add refinements to enforce additional rules
  4. Handle edge cases - Consider how transformations handle null, undefined, edge values
  5. Type safety - Let TypeScript infer types from codec definitions
  6. Async when needed - Use async transforms for I/O operations
Codecs are perfect for API serialization, database value conversion, and any scenario requiring reversible transformations with validation.
Make sure encode and decode functions are true inverses. Non-reversible codecs can lead to data loss or validation errors.