---
url: /backend/validation/intro.md
description: >-
  Runtime validation for API routes - params, payloads and responses derived
  from TypeScript types, read through ctx.validated, and handled in
  api/errors.ts.
---

Backend validation runs on every request an API route handles. The schema comes from the
types you write on the route - no separate schema language and no schema to keep in sync.

```ts [api/users/[id]/index.ts]
export default defineRoute<"users/[id]", [number]>(({ GET }) => [
  GET<{
    query: { include?: "posts" | "comments" }; // [!code hl:2]
    response: [200, "json", User];
  }>(async (ctx) => {
    const { id } = ctx.validated.params; // number
    const { include } = ctx.validated.query;

    return ctx.json(await getUser(id, include));
  }),
]);
```

Validated values land in `ctx.validated.<target>`. A failed check throws a
[`ValidationError`](/backend/validation/error-handling.md), which `api/errors.ts` turns into a response -
usually a `400`.

## What a request can validate

| Target | Where it comes from | Coercion |
|---|---|---|
| [`params`](/backend/validation/params.md) | route params, refined by the `defineRoute` tuple | numbers |
| [`json` / `form` / `raw`](/backend/validation/payload.md) | request body - one body target per handler | native (`json`) or none |
| [`query`](/backend/validation/payload.md#validation-targets) | URL search params | numbers and booleans |
| [`headers` / `cookies`](/backend/validation/payload.md#validation-targets) | request metadata | none |
| [`response`](/backend/validation/response.md) | what the handler returns | native |

Every method handler accepts a type argument object with these keys. A body target on `GET`,
or two body targets on one handler, is reported at dev time and the affected schema is disabled.

## Why it is end-to-end

The same types that validate the request also drive:

* the typed [fetch client](/fetch/intro.md) the frontend calls,
* client-side validation before that call is sent,
* the [OpenAPI 3.1 spec](/openapi/intro.md).

That is the point of [runtype validation](/validation/intro.md): one definition, several outputs.

## Shared concepts

The mechanics are not backend-specific:

* [Runtime validation](/validation/intro.md) - how types become schemas.
* [VRefine](/validation/refine.md) - JSON Schema constraints on any type.
* [Type names](/validation/type-names.md) - what resolves, and what does not.
* [Silent Failure Checklist](/validation/gotchas.md) - mistakes that typecheck and fail at runtime.

## In this section

* [Params](/backend/validation/params.md) - tuple refinements and coercion.
* [Payloads](/backend/validation/payload.md) - body and metadata targets.
* [Responses](/backend/validation/response.md) - declared responses and production policy.
* [Skip Validation](/backend/validation/skip-validation.md) - per-target runtime opt-out.
* [Validation Errors](/backend/validation/error-handling.md) - `ValidationError` and custom messages.
