In Zod 4, what does a z.codec() give you over .transform() when a booking timestamp crosses the network as an ISO string?
answer
- two directions in one schema
- decode on the way in
- encode on the way out
- transforms cannot run backwards
basics
~20 sSince Zod 4.1, z.codec(in, out, { decode, encode }) defines a two-way conversion: parse or decode turns the ISO string into a Date, and encode turns the Date back into a validated string. A .transform() only runs forward, and encoding through one throws.
solid answer
~40 sA codec, added in Zod 4.1, pairs a wire schema and a program schema with a function for each direction: `z.codec(z.iso.datetime(), z.date(), { decode: (s) => new Date(s), encode: (d) => d.toISOString() })`. `parse` and `decode` run the forward conversion, and `encode` (`z.encode` or the `.encode` method) runs it backwards, validating both the `Date` and the string it produces. `decode` and `encode` take strongly typed input, while `parse` accepts `unknown`. Checks and refinements run in both directions, but defaults, prefaults and `.catch()` apply only forward. A `.transform()` anywhere in the schema makes encoding throw an `Error` about a unidirectional transform, which is not a `ZodError`. The pay-off is one definition both client and server import, so the wire format lives in one place.
code
typescript · 14 linesimport * as z from "zod";
const isoToDate = z.codec(z.iso.datetime(), z.date(), {
decode: (iso) => new Date(iso),
encode: (date) => date.toISOString(),
});
const Booking = z.object({ id: z.string(), startsAt: isoToDate });
const booking = Booking.decode({ id: "b1", startsAt: "2026-11-02T09:00:00.000Z" });
console.log(booking.startsAt instanceof Date); // true
const wire = Booking.encode(booking);
// { id: "b1", startsAt: "2026-11-02T09:00:00.000Z" }go deeper
Recall that a codec converts in both directions: decode on the way in, encode on the way out.
Explain how parse, decode and encode differ in direction and input typing, and that codecs arrived in Zod 4.1.
Know what runs in each direction, why a transform or preprocess breaks encoding, and how to share codecs between client and server.
Judge whether one shared two-way schema is worth its coupling, or whether the client and server should own separate one-way schemas.
## The problem a one-way transform leaves A booking's start time travels over the network as an ISO 8601 string, but inside the program you want a `Date`. With a plain transform you can parse in one direction: ```ts const StartsAt = z.iso.datetime().transform((s) => new Date(s)); ``` That covers incoming data only. To send a booking back, you need the reverse conversion, and with a transform that lives somewhere else: - a second schema or a hand-written serializer that must stay in step with the first; - no validation of what you send, so a bad `Date` can reach the wire unnoticed; - two places to change when the wire format changes. ## Defining a codec A **codec**, added in Zod 4.1, is a schema that holds both directions. `z.codec(inputSchema, outputSchema, { decode, encode })` names the wire-side schema, the program-side schema, and a function for each way. ```ts const isoToDate = z.codec(z.iso.datetime(), z.date(), { decode: (iso) => new Date(iso), encode: (date) => date.toISOString(), }); ``` A codec is a schema like any other: it nests inside objects, arrays and pipes, so a whole `Booking` object can be decoded and encoded in one call. ## Decode, encode and parse | Call | Direction | Input type | Calls | |---|---|---|---| | `schema.parse(x)` | Forward | `unknown` | `decode` | | `z.decode(schema, x)` or `schema.decode(x)` | Forward | The schema's input type | `decode` | | `z.encode(schema, x)` or `schema.encode(x)` | Backward | The schema's output type | `encode` | `parse` and `decode` do the same thing at run time; the difference is that `decode` and `encode` take **strongly typed** input, so passing a number where a string belongs is a compile-time error. Use `parse` at a trust boundary, where input really is unknown, and `decode`/`encode` where the value is already typed. Each has safe and async variants (`safeDecode`, `decodeAsync`, `safeEncodeAsync`, and so on). The safe variants return the same success-or-error result as `safeParse()`, so a value that fails validation while encoding is reported as a failed result rather than thrown; the unidirectional-transform error described below is the exception, because it is thrown, not collected. ## What runs in each direction - **The codec's two schemas validate in both directions.** On encode, Zod checks the `Date` against `z.date()`, calls `encode`, then checks the result against `z.iso.datetime()`. - **Checks and refinements run in both directions.** A `.refine()` requiring a future date also guards what you encode. Zod first confirms the value's type, then runs refinements, so your refinement never sees the wrong type. - **Overwrite checks** such as `.trim()` apply in both directions too. - **Defaults, prefaults and `.catch()` apply only forward.** `z.string().default("x").encode(undefined)` fails with a `ZodError`. - **A `.transform()` anywhere in the schema breaks encoding.** Encoding meets the one-way transform and throws an `Error` named `ZodEncodeError` with the message "Encountered unidirectional transform during encode", which is not a `ZodError`. A `z.preprocess()` is built on a transform, so it breaks encoding too. - **Pipes reverse.** A pipe `a.pipe(b)` decodes through `a` then `b`, and encodes through `b` then `a`. ## Composing and sharing codecs 1. Nest codecs in object schemas so a single `decode` turns a whole response into rich types. 2. Use `z.invertCodec()` when you need the same pair the other way round; it swaps the schemas and the two functions, but only for the codec you pass, not codecs nested inside. 3. Copy the ready-made codecs from Zod's documentation (string to number, ISO string to `Date`, JSON string to a schema, base64 to bytes). They are published as copy-and-paste snippets, not as built-in exports. 4. Put the codec schemas in a module both client and server import, so each side decodes what it receives and encodes what it sends with the same definition. ## When a codec is not worth it - Input that only ever flows one way, such as a webhook you never send back: a transform is simpler. - A conversion that loses information, where `encode` cannot reconstruct the original faithfully. - A schema that also needs async database-backed checks, which tie it to the server anyway. How a codec makes the input and output types differ is covered in the lesson on schema-derived types; this lesson keeps the runtime conversion.
- In Zod 4, what happens if a schema you call .encode() on contains a z.preprocess()?Encoding throws an `Error` with the message "Encountered unidirectional transform during encode", because `z.preprocess()` is built on a one-way transform with no reverse function. It is not a `ZodError`, so `safeEncode()` does not turn it into a failed result. Replace the preprocess with a codec, or keep the one-way schema for input only.
- Why would you call z.decode() rather than parse() when both run the same conversion?For the types. `parse()` accepts `unknown`, which is right when data arrives from outside. `z.decode()` requires the schema's input type, so if your code already holds a typed wire object, passing the wrong thing is caught at compile time. Run time behaviour is identical.
- Says z.encode() can reverse any schema, including ones with .transform().
- Believes parse() calls the codec's encode function.
- Thinks defaults and .catch() also fill in values during encoding.
- Expects encoding through a transform to return a ZodError rather than throw.
- Assumes the documented ready-made codecs are built-in Zod exports.
Assumes Zod 4.1 or later: z.codec, z.encode and z.decode were introduced in zod 4.1 and have no Zod 3 equivalent.