# Validate Request Bodies in a Cloudflare Worker

Yes. An agent adds a validator for the JSON body of your Worker's POST route, answers 400 with field errors instead of 500, tests it with Vitest and opens a PR.

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

## What the agent does

The agent reads the Worker's one route before touching it. In a Worker like the `llm-chat-app-template` in cloudflare/templates, `wrangler.jsonc` sets a `compatibility_date` of `2025-10-08`, the `nodejs_compat` and `global_fetch_strictly_public` flags, an `ASSETS` binding on `./public` and an `AI` binding. `src/index.ts` sends anything outside `/api/` to the assets binding, answers `405` for a non-POST on `/api/chat` and `404` elsewhere, and hands POSTs to `handleChatRequest`. That function does `const { messages = [] } = (await request.json()) as { messages: ChatMessage[] }`, a cast with no check, prepends `SYSTEM_PROMPT` when no `system` message is present, and streams `env.AI.run(MODEL_ID, { messages, max_tokens: 1024, stream: true })`. A body that is not JSON, or a `messages` that is a string, throws inside the `try` and comes back as `500 Failed to process request`.

`src/types.ts` already says what a valid message is: `role` is `"system" | "user" | "assistant"` and `content` is a `string`. The agent turns that type into a runtime check in a new `src/validate.ts`, written by hand because the template has no runtime dependencies and the repository's `check:deps` and `check:lockfiles` scripts police `package.json` and the lockfiles across every template; adding `zod` would ripple into `package-lock.json` and the root `pnpm-lock.yaml`. The validator requires a JSON object with a non-empty `messages` array, a `role` from the set, a non-empty string `content`, and limits on the number of messages and total characters that the prompt sets, and returns either the typed value or a list of issues with a path such as `messages[2].content`.

One decision needs a product answer rather than a type: `public/chat.js` only ever sends `user` and `assistant` turns, yet the handler accepts a client-supplied `system` message and skips its own `SYSTEM_PROMPT` when it finds one, so any caller can replace the server's instructions. The prompt below tells the agent to reject `system` from the client with a `400`, and the pull request explains the alternative. Malformed JSON becomes a `400` with `{ error: "invalid_json" }`, a failed check becomes `400` with `{ error: "invalid_request", issues: [...] }`, and the `catch` that returned `500` now covers only the AI call.

The template lists `vitest 4.1.10` and `@cloudflare/vitest-pool-workers 0.21.3` in `devDependencies` and has a `test` script, but no test file and no `vitest.config.ts`; its `tsconfig.json` even excludes a `test` directory that does not exist. The sibling `to-do-list-kv-template` shows the house pattern with its `vitest.config.ts` and `test/tsconfig.json`, so the agent follows it: a `vitest.config.ts` using `defineWorkersConfig` that points at `wrangler.e2e.jsonc`, the variant of the config without the `AI` binding, and `test/chat.test.ts` that imports `SELF` from `cloudflare:test` and POSTs a non-JSON body, an object with no `messages`, a message with a bad `role`, an empty `content`, a client `system` message and an oversized history, asserting `400` and the issue paths, plus a check that `GET /api/chat` is still `405`. The agent runs `npm test` and `npm run check`, which is `tsc --noEmit && wrangler deploy --dry-run`, and pastes both.

## Start it with one API call

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

```json
{
  "agent": "codex",
  "input": "Add request body validation to the /api/chat route of this Cloudflare Worker and open a pull request. Read wrangler.jsonc, wrangler.e2e.jsonc, package.json, tsconfig.json, src/index.ts, src/types.ts and public/chat.js first. Write src/validate.ts by hand with no new dependency: the body must be a JSON object with a non-empty messages array of at most 50 items, each with a role of user or assistant and a non-empty string content, and at most 32000 characters in total. Reject a client-supplied system message so the server's SYSTEM_PROMPT always applies, and explain that choice in the pull request. In src/index.ts answer 400 with { error: \"invalid_json\" } for a body that is not JSON and 400 with { error: \"invalid_request\", issues } naming each failing path for a body that fails the checks, and keep the 500 path for the AI call only. Add vitest.config.ts with defineWorkersConfig pointing at wrangler.e2e.jsonc and a test/tsconfig.json following the to-do-list-kv-template in the same repository, and write test/chat.test.ts using SELF from cloudflare:test covering each rejection and the existing 405 on GET. Run npm test and npm run check and paste both outputs. Do not change public/chat.js, the model id or the streaming response.",
  "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 with a new `src/validate.ts`, a narrower `ChatRequest` type beside `ChatMessage` in `src/types.ts`, a `handleChatRequest` in `src/index.ts` that parses, validates and only then calls the model, and three new files for tests: `vitest.config.ts`, `test/tsconfig.json` and `test/chat.test.ts`. The description pastes the Vitest run with each rejection case listed, and the `tsc --noEmit` and `wrangler deploy --dry-run` output from `npm run check`.

The tests run against the Worker in `workerd` through `@cloudflare/vitest-pool-workers`, using `wrangler.e2e.jsonc` so no `AI` binding is required; validation happens before the model is reached, which is why every case can be exercised without an account. In the templates monorepo the pull request also passes `pnpm run check`, since nothing in `package.json` or a lockfile moved.

A reviewer checks that the limits match what the UI in `public/chat.js` can send and what the model's context allows, that rejecting client `system` messages is the behaviour the product wants, and that the error JSON is something the frontend could show. Then they merge, and a bad request is a `400` with a reason instead of a `500` and a log line.

## Run it on every new Worker with a POST route

A team that stamps out Workers from templates sends one `POST /o/{org}/sessions` per repository with this prompt and that repository in `resources`. Each run reads its own handler and types, so a Worker whose body is a form or a webhook payload gets a validator for that shape, and one that already depends on a schema library gets the schema written in it. Each run opens its own pull request.

Give the API key a `webhook_url` and Rush POSTs `run.completed` when each turn ends, with the `session_url` to read the pull request from. The pasted test output is in the session too, so the reviewer sees which malformed bodies were tried before opening the diff.

## Why run it on Rush?

Validation code is easy to write and easy to leave untested, and a Worker has no local server to poke at by hand without `wrangler dev` and a model binding. In a Rush sandbox the agent runs the Worker under `workerd` through the Vitest pool, sends each malformed body for real and records the status and JSON that came back, so the pull request shows the `400`s rather than asserting them.

The judgment calls are documented in the same place: why no dependency in a monorepo that lints lockfiles, why a client `system` message is refused, what the limits are and where they came from. The same request runs unchanged on the next Worker, in its own sandbox, and a reviewer reads a diff with its evidence attached.

## Frequently asked questions

### Why not zod or valibot?

The template has no runtime dependencies, and the repository's `check:deps` and `check:lockfiles` scripts verify every template's `package.json` and lockfile. A hand-written validator for one object with two fields is a few dozen lines and leaves both untouched. In a standalone Worker that already uses a schema library the agent writes the schema in it instead.

### Why reject a system message from the client?

Because `handleChatRequest` skips `SYSTEM_PROMPT` when the body already has a `system` turn, so any caller could replace the server's instructions. `public/chat.js` never sends one, so nothing legitimate breaks. If your product wants callers to set the system prompt, the prompt says so and the validator allows it.

### How do the tests run without Workers AI?

`vitest.config.ts` points the Workers pool at `wrangler.e2e.jsonc`, the config the template already keeps without the `AI` binding. Every rejection happens before the model is called, so the cases run in `workerd` with no account, and `GET /api/chat` still answers `405`.

### Does the streaming response change?

No. A valid body goes through the same `env.AI.run` call with `stream: true` and the same `text/event-stream` headers. Only the path before it changes, and the `500` handler now covers the AI call alone.

### Where do the limits come from?

From the prompt. Fifty messages and 32,000 characters are the values this request sets, chosen to sit well under the model's context while keeping a long chat working; the validator reads them from two constants at the top of `src/validate.ts` so a reviewer can change them in one place.

## More Cloudflare Workers jobs

- [Add KV Caching to a Cloudflare Worker](https://getrush.ai/run/add-kv-caching/cloudflare-workers/)
- [Add a Queue Consumer to a Cloudflare Worker](https://getrush.ai/run/add-queue-consumer/cloudflare-workers/)
- [Add R2 File Uploads to a Cloudflare Worker from a Linear Issue](https://getrush.ai/run/add-r2-file-uploads/cloudflare-workers/)

## The same job on other stacks

- [Add Input Validation to a Fiber API](https://getrush.ai/run/add-input-validation/fiber/)
- [Add Input Validation to Firebase Cloud Functions](https://getrush.ai/run/add-input-validation/firebase-functions/)
- [Add Input Validation to a Hono API](https://getrush.ai/run/add-input-validation/hono/)

## 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/)
