Skip to content

Backend Validation

1 min read

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.

api/users/[id]/index.ts
ts
export default defineRoute<"users/[id]", [number]>(({ GET }) => [
  GET<{
    query: { include?: "posts" | "comments" };
    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, which api/errors.ts turns into a response - usually a 400.

What a request can validate ​

TargetWhere it comes fromCoercion
paramsroute params, refined by the defineRoute tuplenumbers
json / form / rawrequest body - one body target per handlernative (json) or none
queryURL search paramsnumbers and booleans
headers / cookiesrequest metadatanone
responsewhat the handler returnsnative

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:

That is the point of runtype validation: one definition, several outputs.

Shared concepts ​

The mechanics are not backend-specific:

In this section ​

Released under the MIT License.