# Show Zod Validation Errors From tRPC Under Each Form Field

Yes. An agent adds the flattened Zod issues to the tRPC error shape, reads them on the client with full types, renders one under each field and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-form-validation-errors/trpc/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent starts with how a validation error travels today. In a Next.js Pages Router app laid out like trpc/examples-next-prisma-starter, `src/server/trpc.ts` creates the router with `initTRPC.context<Context>().create({ transformer, errorFormatter({ shape }) { return shape; } })`: the formatter hands back the default shape, so a failed input check reaches the browser as one `BAD_REQUEST` error whose `message` is the Zod issues serialised as JSON. `src/server/routers/post.ts` checks `post.add` with `z.object({ id: z.string().uuid().optional(), title: z.string().min(1).max(32), text: z.string().min(1) })`, and `src/pages/index.tsx` submits that mutation from `AddPostCard` with `addPost.mutateAsync(input)` inside a try/catch. When it fails, the page renders one destructive `Alert` titled "Couldn't add the post" with `addPost.error.message`, and the only hint a person gets beforehand is the `FieldDescription` under the title input, "Up to 32 characters".

It then extends the formatter the way tRPC's error-formatting docs show, with one change for the Zod version the app runs: `package.json` pins `zod` at ^4.2.1, so the agent uses `z.flattenError(error.cause)` rather than the `.flatten()` method Zod 3 apps call. The formatter becomes `errorFormatter({ shape, error })` returning `{ ...shape, data: { ...shape.data, zodError: error.code === 'BAD_REQUEST' && error.cause instanceof ZodError ? z.flattenError(error.cause) : null } }`. Nothing else in the shape moves, so the `httpStatus` that `src/pages/post/[id].tsx` reads from `postQuery.error.data?.httpStatus` keeps working. Because `createTRPCNext<AppRouter, SSRContext>` in `src/utils/trpc.ts` is typed from the router, `addPost.error.data?.zodError?.fieldErrors.title` is `string[] | undefined` on the client with no cast and no shared type to maintain.

In `index.tsx` the agent keeps the uncontrolled form. The file's own comment says a real app would reach for React Hook Form, but that is a different change; this one reads `src/shared-ui/components/field.tsx` to see what error slot its `Field` component offers and renders the first message for `title` and `text` under the matching input in that style, with `aria-invalid` on the input while its message is showing. The general alert stays for an error that carries no `zodError`, such as the `NOT_FOUND` that `post.byId` throws. Since the mutation's `onSuccess` already awaits `utils.post.list.invalidate()`, a corrected resubmission still refreshes the list.

For proof the agent extends `playwright/smoke.test.ts`, which already has `go to /` and `add a post`, with a test that fills a 40-character title, submits, and expects a message under the Title field and no destructive alert. In its sandbox it installs Postgres, sets `DATABASE_URL` and `DIRECT_URL` as `.env` names them, runs `pnpm install`, `pnpm prebuild` (which `package.json` defines as `prisma generate` then `prisma migrate deploy`), `pnpm typecheck`, `pnpm lint` (oxlint in type-aware mode), `pnpm test-unit` and `pnpm build` followed by `pnpm test-e2e`, since `playwright.config.ts` starts `npm run start` when `CI` is set. The pull request description quotes each command's result.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Show Zod validation errors from tRPC under each form field. Read src/server/trpc.ts, src/server/routers/post.ts, src/pages/index.tsx, src/shared-ui/components/field.tsx and src/utils/trpc.ts first. In the errorFormatter, add data.zodError holding the flattened issues when error.cause is a ZodError and keep the rest of the shape as it is; this app is on Zod 4, so use z.flattenError. In AddPostCard, render each field's first message under its input with aria-invalid on the input, and keep the general alert for errors that carry no zodError. Add a Playwright test that submits a 40-character title and expects a message under Title and no alert. Run pnpm typecheck, pnpm lint, pnpm test-unit and pnpm test-e2e against a local Postgres, quote the results and open a pull request.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request that touches `src/server/trpc.ts`, `src/pages/index.tsx`, `playwright/smoke.test.ts` and, if the field component had no error slot, `src/shared-ui/components/field.tsx`. The router files are untouched: the Zod schemas in `post.ts` already say what is valid, and the change only carries their verdict to the screen. The description quotes the output of each command the agent ran and names the test it added.

The repository's `Testing` workflow in `.github/workflows/main.yml` runs on every push with two jobs, `Build + E2E tests` and `Unit tests + typecheck`, each against a Postgres service container, so the pull request shows both checks beside the agent's own run. The run's record keeps the full Playwright output and the oxlint report, which a reviewer can open without rerunning anything.

Before merging, a reviewer decides two things the agent leaves as they are: whether Zod's default messages are what people should read, or whether `post.ts` should carry its own, such as `z.string().min(1, 'Give the post a title')`, and whether the general alert should still show for a `BAD_REQUEST` that has field messages. Both are one-line follow-ups once the messages are on the page.

## Run it on every Linear issue labelled ux

In the Project that holds the repository, create an automation whose saved prompt is a general version of this page's request, with a `linear` trigger on `linear.issue.labeled` and `ux` in its `labels`. The trigger places the labelled issue after the prompt and fills nothing in, so the prompt says: read the issue that follows, make the change it describes in this repository's forms and procedures, prove it with a Playwright test, and open a pull request that links the issue. The automation runs with its runner's Linear connection, made in the console under Settings → Connections, and fires only when someone in your Rush org adds the label.

A designer who files "the add-post form should say which field is wrong" and adds the label starts one run; a second issue about the post page's 404 copy starts another, each on its own branch with its own pull request. Runs past the automation's max runs per hour wait as `queued` rather than being dropped.

## Why run it on Rush?

Seeing the error on screen needs the whole stack up: Postgres with the four migrations applied, the Prisma client generated, the Next.js build and a Chromium that Playwright drives. A sandbox that starts clean installs all of it, runs the test and keeps the output, so the pull request opens with the proof in it rather than a promise to test later.

The run's record holds every command and its output, including the oxlint type-aware pass that `pnpm lint` runs and the per-test Playwright lines, so a reviewer checks what happened rather than trusting a summary. Across a team's tRPC apps the same request runs at once, one sandbox each, and each pull request shows that app's own form fields with their own messages.

## Frequently asked questions

### Does this change the error shape for every procedure?

Yes, the formatter in `src/server/trpc.ts` is global. The `zodError` field is filled only when the error's code is `BAD_REQUEST` and its cause is a ZodError, which is what tRPC produces for a failed `.input()` check; every other error gets `zodError: null` and keeps the rest of its shape unchanged.

### Why not move the form to React Hook Form while in there?

The comment in `index.tsx` suggests it, and it would be a fair follow-up issue. This change is about carrying the server's verdict to the field, which works with the existing `FormData` form, so the pull request stays small enough to review in one sitting.

### Will these errors be logged on the server?

No. The `onError` hook in `src/pages/api/trpc/[trpc].ts` logs only `INTERNAL_SERVER_ERROR`. A `BAD_REQUEST` from input validation is the client's mistake, so it stays out of the log, as it does today.

### Does the shape survive the batch stream link and superjson?

Yes. `src/utils/trpc.ts` uses `httpBatchStreamLink` with the superjson transformer; each call in a batch carries its own error, and the flattened issues are plain strings and arrays, which superjson passes through unchanged.

### What if my app is still on Zod 3?

The agent reads the version in `package.json` first. On Zod 3 it calls `error.cause.flatten()`, which returns the same `{ formErrors, fieldErrors }` shape, and the client code is identical.

## More tRPC jobs

- [Add Health Check Endpoints to a tRPC and Next.js App](https://getrush.ai/run/add-health-checks/trpc/)
- [Add ESLint and Prettier Checks to CI for a tRPC App](https://getrush.ai/run/add-lint-to-ci/trpc/)
- [Generate OpenAPI Docs from a tRPC Router](https://getrush.ai/run/add-openapi-docs/trpc/)

## More jobs like this: Turn a Linear label into a PR

- [Add Form Validation to a SolidJS App](https://getrush.ai/run/add-form-validation/solidjs/)
- [Add Full-Text Search to a Drizzle and PostgreSQL App](https://getrush.ai/run/add-full-text-search/drizzle/)
- [Add Full-Text Search to a Prisma App](https://getrush.ai/run/add-full-text-search/prisma/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
