Last Updated: 3/12/2026
Codecs
Codecs provide bidirectional transformations — both encoding (output → input) and decoding (input → output).
Basic Codecs
import * as z from "zod";
const Base64Codec = z.codec(
z.string(), // input type (base64 string)
z.string(), // output type (plain string)
{
decode: (base64) => Buffer.from(base64, "base64").toString("utf-8"),
encode: (plain) => Buffer.from(plain, "utf-8").toString("base64"),
}
);
const decoded = Base64Codec.parse("SGVsbG8="); // => "Hello"
const encoded = Base64Codec.encode("Hello"); // => "SGVsbG8="Parsing vs. Encoding
.parse()/.decode(): Input → Output.encode(): Output → Input
codec.parse(input); // decode
codec.decode(input); // same as parse
codec.encode(output); // reverse transformationUse Cases
Codecs are useful for:
- Serialization formats (JSON, base64, protobuf)
- Data normalization (timestamps, currencies)
- Reversible transformations where you need both directions
Codecs vs. Transforms
- Transforms: One-way (input → output)
- Codecs: Two-way (input ⇄ output)
Use transforms when you only need decoding. Use codecs when you need both directions.
What’s Next
- Transforms — One-way data conversion
- Type Inference — Understand input vs output types