Skip to content
rest-rpc
Esc
↑↓navigate↵open⌘Jpreview
On this page

Validation

What is validated, when, and which type each side sees.

Schemas are any Standard Schema, 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:

const 
const list: HandledRoute<{
    readonly method: "GET";
    readonly path: "/posts";
    request: {
        query: readonly [z.ZodObject<{
            page: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
        }, z.core.$strip>];
    };
    responses: {
        200: {
            body: z.ZodObject<{
                items: z.ZodArray<z.ZodObject<{
                    id: z.ZodString;
                    title: z.ZodString;
                    body: z.ZodString;
                }, z.core.$strip>>;
                total: z.ZodNumber;
            }, z.core.$strip>;
        };
    };
    readonly metaShape?: DefaultMeta | undefined;
}, DefaultContext, DefaultContext, {
    items: z.infer<typeof post>[];
    total: number;
}>
list
= const route: Omit<ServerRouteBuilder<RootBuilderState, DefaultContext, DefaultContext>, "meta">
Entry point for defining routes with handlers.
@remarksResponses are inferred from the handler unless they are defined before `.handler()`. Routes are runtime-independent: the same route works with the Fetch and Node HTTP handlers.@see{@link https://rest-rpc.vercel.app/docs/quickstart#define-routes}
route
.get<"/posts">(path?: "/posts" | undefined): Omit<ServerRouteBuilder<WithHttpMethod<RootBuilderState, "GET", "/posts">, DefaultContext, DefaultContext>, OmittedMethods<WithHttpMethod<RootBuilderState, "GET", TPath>>>
Defines a GET route.
@see{@link https://rest-rpc.vercel.app/docs/route-builder}
get
("/posts")
.
query<z.ZodObject<{
    page: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
}, z.core.$strip>>(schema: z.ZodObject<{
    page: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
}, z.core.$strip>): Omit<ServerRouteBuilder<WithRequest<WithHttpMethod<RootBuilderState, "GET", "/posts">, "query", z.ZodObject<{
    page: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
}, z.core.$strip>>, DefaultContext, DefaultContext>, "static" | OmittedMethods<WithRequest<WithHttpMethod<RootBuilderState, "GET", "/posts">, "query", TSchema>>>
Defines URL query parameters.
@see{@link https://rest-rpc.vercel.app/docs/route-builder#request}
query
(import zz.
function object<{
    page: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
}>(shape?: {
    page: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
} | undefined, params?: string | {
    error?: string | z.core.$ZodErrorMap<NonNullable<z.core.$ZodIssueInvalidType<unknown> | z.core.$ZodIssueUnrecognizedKeys>> | undefined;
    message?: string | undefined | undefined;
} | undefined): z.ZodObject<{
    page: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
}, z.core.$strip>
object
({ page: z.ZodDefault<z.ZodCoercedNumber<unknown>>page: import zz.import coercecoerce.function number<unknown>(params?: string | z.core.$ZodNumberParams): z.ZodCoercedNumber<unknown>number()._ZodNumber<$ZodNumberInternals<unknown>>.int(params?: string | z.core.$ZodCheckNumberFormatParams): z.ZodCoercedNumber<unknown>
Consider `z.int()` instead. This API is considered *legacy*; it will never be removed but a better alternative exists.
int
()._ZodNumber<$ZodNumberInternals<unknown>>.min(value: number, params?: string | z.core.$ZodCheckGreaterThanParams): z.ZodCoercedNumber<unknown>min(1).ZodType<any, any, $ZodNumberInternals<unknown>>.default(def: number): z.ZodDefault<z.ZodCoercedNumber<unknown>> (+1 overload)default(1) }))
.
response<z.ZodObject<{
    items: z.ZodArray<z.ZodObject<{
        id: z.ZodString;
        title: z.ZodString;
        body: z.ZodString;
    }, z.core.$strip>>;
    total: z.ZodNumber;
}, z.core.$strip>, undefined>(schema: z.ZodObject<{
    items: z.ZodArray<z.ZodObject<{
        id: z.ZodString;
        title: z.ZodString;
        body: z.ZodString;
    }, z.core.$strip>>;
    total: z.ZodNumber;
}, z.core.$strip>, options?: undefined): Omit<ServerRouteBuilder<WithResponse<WithRequest<WithHttpMethod<RootBuilderState, "GET", "/posts">, "query", z.ZodObject<{
    page: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
}, z.core.$strip>>, {
    ...;
}, undefined>, DefaultContext, DefaultContext>, "static" | OmittedMethods<...>> (+3 overloads)
Defines a successful response, JSON unless its headers declare a `content-type`. The status defaults to 200.
@see{@link https://rest-rpc.vercel.app/docs/route-builder#defined-responses}
response
(import zz.
function object<{
    items: z.ZodArray<z.ZodObject<{
        id: z.ZodString;
        title: z.ZodString;
        body: z.ZodString;
    }, z.core.$strip>>;
    total: z.ZodNumber;
}>(shape?: {
    items: z.ZodArray<z.ZodObject<{
        id: z.ZodString;
        title: z.ZodString;
        body: z.ZodString;
    }, z.core.$strip>>;
    total: z.ZodNumber;
} | undefined, params?: string | {
    error?: string | z.core.$ZodErrorMap<NonNullable<z.core.$ZodIssueInvalidType<unknown> | z.core.$ZodIssueUnrecognizedKeys>> | undefined;
    message?: string | undefined | undefined;
} | undefined): z.ZodObject<...>
object
({
items: z.ZodArray<z.ZodObject<{
    id: z.ZodString;
    title: z.ZodString;
    body: z.ZodString;
}, z.core.$strip>>
items
: import zz.
function array<z.ZodObject<{
    id: z.ZodString;
    title: z.ZodString;
    body: z.ZodString;
}, z.core.$strip>>(element: z.ZodObject<{
    id: z.ZodString;
    title: z.ZodString;
    body: z.ZodString;
}, z.core.$strip>, params?: string | z.core.$ZodArrayParams): z.ZodArray<z.ZodObject<{
    id: z.ZodString;
    title: z.ZodString;
    body: z.ZodString;
}, z.core.$strip>>
array
(
const post: z.ZodObject<{
    id: z.ZodString;
    title: z.ZodString;
    body: z.ZodString;
}, z.core.$strip>
post
), total: z.ZodNumbertotal: import zz.function number(params?: string | z.core.$ZodNumberParams): z.ZodNumbernumber() }))
.
handler<{
    items: z.infer<typeof post>[];
    total: number;
}>(handler: HandlerFor<{
    readonly method: "GET";
    readonly path: "/posts";
    request: {
        query: readonly [z.ZodObject<{
            page: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
        }, z.core.$strip>];
    };
    responses: {
        200: {
            body: z.ZodObject<{
                items: z.ZodArray<z.ZodObject<{
                    id: z.ZodString;
                    title: z.ZodString;
                    body: z.ZodString;
                }, z.core.$strip>>;
                total: z.ZodNumber;
            }, z.core.$strip>;
        };
    };
    readonly metaShape?: DefaultMeta | undefined;
}, DefaultContext, {
    items: z.infer<typeof post>[];
    total: number;
}>): HandledRoute<...>
Attaches the server handler that completes the route.
@see{@link https://rest-rpc.vercel.app/docs/route-builder#responses}
handler
(({
query: {
    page: number;
}
query
}) =>
function listPosts(page: number): {
    items: z.infer<typeof post>[];
    total: number;
}
listPosts
(
query: {
    page: number;
}
query
.page: numberpage));
const {
const body: {
    items: {
        id: string;
        title: string;
        body: string;
    }[];
    total: number;
}
body
} = await
const client: {
    list: (request?: {
        query?: {
            page?: unknown;
        } | undefined;
    } | undefined, options?: FetchOptions | undefined) => ClientPromise<{
        status: 200;
        body: {
            items: {
                id: string;
                title: string;
                body: string;
            }[];
            total: number;
        };
        headers: Record<string, string>;
        cookies: readonly string[];
    }, Error>;
}
client
.
list: (request?: {
    query?: {
        page?: unknown;
    } | undefined;
} | undefined, options?: FetchOptions | undefined) => ClientPromise<{
    status: 200;
    body: {
        items: {
            id: string;
            title: string;
            body: string;
        }[];
        total: number;
    };
    headers: Record<string, string>;
    cookies: readonly string[];
}, Error>
list
({
query?: {
    page?: unknown;
} | undefined
query
: { page?: unknownpage: 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.

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

createApp(router, {
	disableRequestValidation: true,
	disableResponseValidation: true,
});
  • 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:

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.

Was this page helpful?