In Zod 4, what is the difference between adding .refine() and adding .transform() to a schema?
answer
- check versus conversion
- what comes out of parse
- falsy return, custom issue
- a pipe into z.transform
basics
~20 sIn Zod 4, .refine() adds a custom check: its function returns truthy or falsy, the value passes through unchanged, and a falsy result records an issue with code custom. .transform() replaces the validated value with whatever its function returns.
solid answer
~50 s`.refine(fn, { error })` is a **check**: Zod calls `fn` with a value that already has the schema's type, and a falsy return adds one issue with code `"custom"` while the value itself is left alone. `.transform(fn)` is a **conversion**: in Zod 4 it is shorthand for piping the schema into `z.transform(fn)`, so it runs only when nothing before it raised an issue, and parsing returns the function's result, such as a trimmed price string turned into a `number`. Neither function should throw, because Zod does not catch thrown errors: a refinement signals failure by returning falsy, and a transform reports a problem by pushing an issue onto `ctx.issues` and returning `z.NEVER`. The working rule is simple: if the value should come out the same, refine it; if it should come out different, transform it.
code
typescript · 7 linesimport * as z from "zod";
const HasAt = z.string().refine((s) => s.includes("@"), { error: "Missing @" });
HasAt.parse("[email protected]"); // "[email protected]" (unchanged)
const Length = z.string().transform((s) => s.length);
Length.parse("[email protected]"); // 15 (converted)go deeper
Remember the split: refine says yes or no and keeps the value, transform returns a new value. Be ready to say what parse returns in each case.
Explain that a refinement's issue is continuable by default, that abort stops later checks, and that a transform is a pipe which never runs after an earlier issue.
Show you know why neither function may throw, how ctx.issues with z.NEVER reports a failed conversion, and how chain order decides which value a refinement inspects.
Talk about keeping schemas declarative: built-in checks stay visible to anything that reads the schema, while transforms make input and output differ, which shapes how a team shares one schema across layers.
## Two different jobs Zod 4 schemas do two kinds of work after the basic type check. A **refinement** asks a yes-or-no question about a value the schema has already accepted ("is this string at most 255 characters?", "does the confirmation equal the password?"). A **transform** turns the accepted value into something else ("trim this", "turn the text `"19.99"` into the number `19.99`"). `.refine()` and `.transform()` are the everyday methods for each job, and mixing them up is the most common way a schema ends up returning the wrong thing. ## How .refine() behaves `.refine(fn, params)` appends a custom check to the schema's list of checks. - **Return value is a verdict.** Zod treats a truthy return as a pass and a falsy one as a failure. The return value never becomes the parsed value: `z.string().refine((s) => s.includes("@")).parse("[email protected]")` returns the string, not `true`. - **Failure produces one issue** with code `"custom"`. The `error` option sets its message, either as a string or as a function of the issue. - **Other checks keep running.** By default a refinement's issue is *continuable*, so later checks still execute and Zod reports as many problems as it can at once. `abort: true` makes a failing refinement stop the checks after it. - **It is skipped after a type failure.** If the value never got past the type check (a number where a string was expected), refinements do not run, so your function never receives a value of the wrong type. - **`path` re-targets the issue**, which matters on object schemas for cross-field rules. ## How .transform() behaves `.transform(fn)` is sugar for `schema.pipe(z.transform(fn))`, and the method returns a pipe. - **It runs only on clean input.** A pipe stops as soon as the schema on its left reports an issue, so a transform never sees a value that failed validation. The single exception is an unknown-key issue from a strict object, which describes extra keys rather than the value. - **Its return value is the new value.** Whatever the function returns is what `parse` hands back, and any refinement chained *after* the transform sees the converted value. - **Problems are reported through `ctx`.** The second argument lets you push an issue onto `ctx.issues`; returning `z.NEVER` then exits without affecting the result's type. - **Async functions need the async parse methods** (`parseAsync`, `safeParseAsync`); a synchronous parse throws when it meets one. ## Order matters when you chain them Checks and transforms run in the order you write them. Consider a price field: ```ts const Price = z .string() .trim() .min(1, { error: "Price is required" }) .transform((s) => Number(s)) .refine((n) => Number.isFinite(n) && n > 0, { error: "Price must be a positive number" }); Price.parse(" 19.99 "); // 19.99 Price.parse("abc"); // ZodError: Price must be a positive number ``` 1. `.trim()` and `.min(1)` run on the string. 2. If neither raised an issue, the transform converts the string to a number. 3. The final `.refine()` runs on the number, because it is attached after the transform. Move the refinement before the transform and its function would receive the string instead. ## Side by side | | `.refine()` | `.transform()` | |---|---|---| | Purpose | Accept or reject | Convert | | What `parse` returns | The same value | The function's return value | | How it fails | Falsy return, one `"custom"` issue | Push onto `ctx.issues`, return `z.NEVER` | | Runs when earlier checks failed | Yes, after continuable issues; no after a type failure | No, any earlier issue stops the pipe | | Built on | A custom check in the schema | A pipe into `z.transform()` | ## Mistakes to avoid - Returning a converted value from `.refine()` and expecting `parse` to return it. - Returning `false` from a transform to signal failure: `false` simply becomes the output. - Throwing inside either function. Zod does not catch thrown errors, so the exception escapes `parse` and even `safeParse`. - Writing a custom function for a rule that a built-in such as `.min()`, `.max()` or `.regex()` already expresses. Built-in checks are visible on the schema, for example as a string schema's `minLength` property, while a custom function is opaque. How a transform changes the static input and output types is covered in the lesson on schema-derived types; this lesson keeps the runtime behaviour.
- In Zod 4, how do you report a failed conversion from inside a .transform()?Use the second argument. Push an issue such as `{ code: "custom", message: "Not a number", input: val }` onto `ctx.issues`, then return `z.NEVER`. That records a normal issue, so `safeParse` returns a failure, and `z.NEVER` lets the function exit without widening its return type. Throwing does not work, because Zod does not catch thrown errors.
- If a refinement is chained after a transform, which value does it see?The transformed one. `.transform()` returns a pipe, and a `.refine()` called on that pipe attaches a check that runs on the pipe's output. So `z.string().transform(Number).refine((n) => n > 0)` receives a number. Put the refinement before the transform if it needs the original string.
- Says the value a refine function returns becomes the parsed value.
- Returns false from a transform to make parsing fail.
- Throws inside a refinement and expects Zod to turn it into an issue.
- Believes a transform still runs when the schema before it reported an issue.
- Thinks the first failed refinement always stops every later check.