---
title: Validation
description: What is validated, when, and which type each side sees.
---

Schemas are any [Standard Schema](https://standardschema.dev), such as Zod,
Valibot or ArkType. A schema has an input type and an output type, and each
side of a route sees one of them:

```ts twoslash
import { createClient } from "@rest-rpc/core";
import { route } from "@rest-rpc/server";
import * as z from "zod";
const post = z.object({ id: z.string(), title: z.string(), body: z.string() });
declare function listPosts(page: number): {
	items: z.infer<typeof post>[];
	total: number;
};
// ---cut---
const list = route
	.get("/posts")
	.query(z.object({ page: z.coerce.number().int().min(1).default(1) }))
	.response(z.object({ items: z.array(post), total: z.number() }))
	.handler(({ query }) => listPosts(query.page));
// ---cut-start---
const client = createClient({ list }, { origin: "http://localhost" });
// ---cut-end---

const { body } = await client.list({ query: { page: 1 } });
```

- What you send is the **input**: a client call's request, and a handler's
  return value.
- What you receive is the **output**: a handler's arguments, and a client
  call's result.

## Requests

The server validates params, query, headers and body before middleware and
the handler run.

- A failure is answered with `REQUEST_VALIDATION_FAILED` and status `400`, and
  the handler doesn't run.
- Params, query and headers arrive as strings, so their schemas coerce.

:::warning
A schema that keeps unknown keys, such as `z.looseObject()`, passes on
anything the request sent, `__proto__` included. Don't deep-merge such a body
into another object.
:::

## Responses

- Responses defined with `.response()` are validated before they're sent, and
  stream events as they're yielded.
- A failure is a server bug, so the client gets a plain
  `INTERNAL_SERVER_ERROR`, and the issues stay on the server.
- Responses inferred from the handler are type-checked but not validated.
- A headers schema decides which headers are sent. `z.object()` sends only
  the ones it declares.

## Disabling Validation

```ts
createApp(router, {
	disableRequestValidation: true,
	disableResponseValidation: true,
});
```

:::warning
Coercions, transforms and defaults don't apply, though the types say they
did. With the route above, `query.page` would be the string `"1"`, or
`undefined`. Disable validation only with schemas that don't change values.
:::

- A route with a body accepts any content type.
- Errors are still validated when they're created.

## Types Without Validation

`type<T>()` is a schema that only carries a type:

```ts
import { type } from "@rest-rpc/server";

const create = route
	.post("/posts")
	.body(type<{ title: string; body: string }>()) // accepted as is
	.handler(({ body }) => createPost(body));

const idToString = type((id: number) => String(id)); // input number, output string
```

The optional function maps input to output, and may be async.
