In Zod 4, how do z.flattenError and z.treeifyError turn a ZodError into field messages for a sign-up form, and when does each fit?
answer
- one level versus the whole shape
- form-level versus field-level
- first path segment only
- properties and items
- an optional mapper argument
basics
~20 sz.flattenError returns formErrors for root-level issues and fieldErrors keyed by each issue's first path segment, which suits a flat form. z.treeifyError returns a nested errors/properties/items tree mirroring the schema, which suits nested objects and arrays.
solid answer
~40 sBoth are top-level Zod 4 functions that take a ZodError. `z.flattenError(err)` returns `{ formErrors, fieldErrors }`: issues whose `path` is `[]`, such as an unrecognized key on a `z.strictObject`, go into `formErrors`, and every other issue goes into `fieldErrors` under the **first** segment of its path. That is ideal for a one-level sign-up form, but a failure at `address.zip` lands under `fieldErrors.address` with no sign of which sub-field failed. `z.treeifyError(err)` returns a tree that mirrors the schema: each node has `errors`, objects add `properties`, arrays add `items`, so you read `tree.properties?.address?.properties?.zip?.errors` with optional chaining. Both accept a mapper, `(issue) => U`, when you want the code or parameters instead of just the message. They replace the deprecated `.flatten()` and `.format()` methods.
code
typescript · 25 linesimport * as z from "zod";
const SignUp = z.object({
email: z.email(),
password: z.string().min(8),
address: z.object({ city: z.string(), zip: z.string().length(5) }),
});
const result = SignUp.safeParse({
email: "[email protected]",
password: "short",
address: { city: "Leeds", zip: "123" },
});
if (!result.success) {
const flat = z.flattenError(result.error);
console.log(flat.fieldErrors.password);
// [ 'Too small: expected string to have >=8 characters' ]
console.log(flat.fieldErrors.address);
// [ 'Too small: expected string to have exactly 5 characters' ] (no sign it was zip)
const tree = z.treeifyError(result.error);
console.log(tree.properties?.address?.properties?.zip?.errors);
// [ 'Too small: expected string to have exactly 5 characters' ]
}go deeper
Recall that z.flattenError gives formErrors and fieldErrors for a flat form, and that z.treeifyError gives a nested tree for deeper data.
Explain the grouping rule: empty paths go to formErrors and everything else is keyed by the first path segment, so nested failures collapse onto their parent field.
Show you pick the helper by the form's shape, pass a mapper when clients need codes, and know the deprecated methods and their replacements when reading older code.
Consider which shape the team standardises on for clients, since the choice decides whether nested inputs can ever be highlighted precisely without a later contract change.
## The problem they solve A **ZodError** carries an `issues` array: one object per problem, each with a `code`, a `path` (keys and array indexes from the root) and a `message`. A form does not want an array. It wants to ask "what is wrong with the password field?" and get a list of messages. Zod 4 ships two top-level functions that regroup issues by path: `z.flattenError` and `z.treeifyError`. A third, `z.prettifyError`, produces a printable string rather than a lookup structure. ## z.flattenError: one level deep `z.flattenError(error)` returns: ```ts { formErrors: string[]; fieldErrors: { [key in keyof T]?: string[] } } ``` The grouping rule is simple and worth stating exactly: - An issue whose `path` is empty (`[]`) goes into **`formErrors`**. Typical sources are an unrecognized key on a `z.strictObject`, or a failure attached to the object as a whole. - Every other issue goes into **`fieldErrors`**, under the **first element** of its path only. - Several issues on the same field are pushed into the same array, in issue order. For a sign-up form whose fields are all one level deep (email, password, display name), this is exactly the right shape: `fieldErrors.password` is the list to render under the password input. The cost appears with nesting. An issue at `['address', 'zip']` lands in `fieldErrors.address`, and an issue at `['phones', 1]` lands in `fieldErrors.phones`. The message survives, but the information about *which* sub-field or element failed is gone from the structure. ## z.treeifyError: the whole shape `z.treeifyError(error)` builds a nested object that mirrors the schema: - every node has an **`errors`** array for issues located exactly there; - object nodes add **`properties`**, keyed by field name; - array and tuple nodes add **`items`**, indexed by position; - root-level issues go into the top node's `errors`. Branches exist only where issues occurred, so reads need optional chaining: `tree.properties?.phones?.items?.[1]?.errors`. The tree never loses location, which makes it the right choice for nested objects, arrays of rows, or any form whose inputs map to deep paths. One behaviour to know: for a plain union that matched no option, `treeifyError` walks into the issues of every option it tried, so the tree can mix errors from branches the user never intended. `flattenError` does not walk into them; it records the union issue's own message once, keyed like any other issue. ## Choosing between them | | `z.flattenError` | `z.treeifyError` | |---|---|---| | Shape | `formErrors` + `fieldErrors` | nested `errors` / `properties` / `items` | | Location kept | first path segment only | full path | | Root-level issues | `formErrors` | top-level `errors` | | Best for | flat forms | nested objects and arrays | | Reading | `flat.fieldErrors.email` | `tree.properties?.email?.errors` | A practical rule of thumb: 1. If every input in the form is a direct property of the schema, use `z.flattenError`. 2. If any input sits inside a nested object or an array, use `z.treeifyError`, or walk `issues` yourself keyed by the full path. 3. Never infer a sub-field from a flattened message; the structure no longer carries it. ## Keeping more than the message Both functions take an optional second argument, a **mapper** from issue to any value. The default maps each issue to its `message`. Passing `(issue) => ({ code: issue.code, message: issue.message })` keeps the machine-readable code next to the text, which a client can use for its own wording or translation. How that object is then shaped into an HTTP response body is a separate API-design decision. ## Pitfalls when rendering - **Arrays, not strings.** Each field maps to an array, because one value can fail several checks at once (a password that is too short and also misses a required pattern). Decide whether the form shows the first message or all of them. - **Absent means clean.** A field without issues has no key in `fieldErrors` and no node in the tree. Treat `undefined` as "no errors", never as a crash. - **Typed keys.** The `fieldErrors` keys are typed from the schema's output type, so a misspelt field name is a compile error rather than a silently empty lookup. - **Root messages need a home.** A form that renders only per-field messages will hide `formErrors` entirely; give them a banner or summary area. ## What changed from Zod 3 In Zod 3 these were methods on the error: `error.flatten()` and `error.format()`. In Zod 4 both methods still exist on the `ZodError` class but are **deprecated**; the top-level functions are the supported API. `z.formatError`, the function form of the old `.format()` output with its `_errors` keys, is deprecated as well in favour of `z.treeifyError`, whose shape is different: `errors`, `properties` and `items`. Zod 4 also dropped the undocumented `formErrors` property on the error and the `errors` alias for `issues`.
- In Zod 4, how would you keep each issue's code in a flattened error?Pass a mapper as the second argument: `z.flattenError(err, (issue) => ({ code: issue.code, message: issue.message }))`. Each field's array then holds those objects instead of strings, so a client can choose its own wording from the code while still having Zod's default text.
- When would you skip both helpers and read issues directly?When a consumer needs the full path as a key, for example a form library that addresses inputs as `phones.1.number`, or a log line per issue. Iterating `error.issues` and joining each `path` gives that mapping without losing location, which `flattenError` would.
z.flattenError sorts letters into pigeonholes by street name only, so mail for 12 Park Road and 40 Park Road shares one Park Road slot. z.treeifyError keeps the full address: street, then house number, then flat.
- z.flattenError keeps nested paths such as address.zip as separate keys.
- Zod 4 removed ZodError.flatten() outright.
- z.treeifyError returns the _errors shape that Zod 3's format() produced.
- z.flattenError silently drops issues that have an empty path.
- The formatters can only return strings, so codes are always lost.
Assumes Zod 4; z.flattenError and z.treeifyError replace Zod 3's ZodError.flatten() and .format() methods, which still exist but are deprecated.