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

Route Builder

Define a route's method, path, request, responses and handler.

A route is a chain of builder calls that ends with .handler(). Schemas are any Standard Schema, such as Zod, Valibot or ArkType.

Defaults

import { route } from "@rest-rpc/server";
import * as z from "zod";

const create = route
	.body(z.object({ title: z.string(), body: z.string() }))
	.handler(({ body }) => createPost(body));

export const router = { posts: { create } }; // POST /posts/create
  • No method means POST.
  • No path means the route’s keys in the route tree, such as /posts/create.
  • A returned value is a JSON body with status 200.
  • Route trees are plain objects, so split them into modules and combine them however you like.

Method and Path

const search = route
	.get("/posts/search")
	.query(z.object({ term: z.string() }))
	.handler(({ query }) => searchPosts(query.term));

const get = route
	.get("/posts/:id")
	.handler(({ params }) => findPost(params.id));

const list = route.get().handler(() => listPosts()); // GET, path from its keys
  • The methods are .get(), .post(), .put(), .patch() and .delete().
  • :name segments are string params unless .params() defines them.
  • Wildcards and regular expressions aren’t supported.

Request

const update = route
	.patch("/posts/:id")
	.params(z.object({ id: z.string() }))
	.query(z.object({ notify: z.stringbool().optional() }))
	.headers(z.object({ "x-request-id": z.string().optional() }))
	.body(z.object({ title: z.string() }))
	.handler(({ params, query, headers, body }) =>
		updatePost(params.id, body.title, query.notify),
	);
  • Params, query and headers arrive as strings, so their schemas coerce. See Content Types.
  • .params() keys can’t be optional, and need matching :name segments.
  • GET routes have no .body().
  • Header names are lowercase. An uppercase name is a type error.

Responses

Return the body, or respond() to also set the status, headers or cookies:

const create = route
	.post("/posts")
	.body(z.object({ title: z.string(), body: z.string() }))
	.handler(({ body, respond }) => {
		const post = createPost(body);
		return respond(post, {
			status: 201, // 200 to 299
			headers: { location: `/posts/${post.id}` },
			cookies: ["seen=1; HttpOnly"],
		});
	});

What a handler returns decides the response:

  • undefined: no body.
  • An async iterable: a stream.
  • A Fetch Response: sent as it is. See Raw Responses.
  • Anything else: a JSON body. An object with a status field is still just a body; only respond() sets the status.

Errors are thrown, not returned. See Errors.

Inferred Responses

Without .response(), the client’s result type is whatever the handler returns. Nothing is validated at runtime.

Defined Responses

.response(schema, options) defines a response. It types the handler and the client, and is validated before it’s sent:

route
	.post("/posts")
	.body(z.object({ title: z.string(), body: z.string() }))
	.response(postSchema, {
		status: 201,
		headers: z.object({ location: z.string() }),
	})
	.response({ status: 202 }) // no body
	.handler(({ body, respond }) => {
		if (needsReview(body)) return respond(undefined, { status: 202 });
		const post = createPost(body);
		return respond(post, {
			status: 201,
			headers: { location: `/posts/${post.id}` },
		});
	});
  • status defaults to 200.
  • A response without a body takes only options: .response() or .response({ status: 204 }).
  • With one defined response, the handler can return the body directly. With several, it uses respond() with one of their statuses.
  • A headers schema decides which headers are sent: z.object() sends only the ones it declares.

Raw Responses

Return a Fetch Response for what the builder can’t describe, such as a redirect:

route
	.get("/images/:id")
	.handler(async ({ params }) =>
		Response.redirect(await signedUrl(params.id), 302),
	);
  • The request is still validated and middleware still runs.
  • The response is sent as it is, without validation.
  • Returning a Response on any path makes the route’s result untyped: status: number and body: unknown. Defined errors stay typed.
  • In a contract, declare it with .response(raw({ description })).

Static Responses

.static(value) completes a route whose response never changes. It’s validated and serialized once, at startup:

route.get("/health").static({ ok: true });
route
	.get("/robots.txt")
	.static(
		respond("User-agent: *", { headers: { "content-type": "text/plain" } }),
	);
  • It can’t be a function, promise or stream, and the route can’t read the request.
  • Its schemas and codecs have to be synchronous.

Stacking Calls

Every call returns a new builder, so a partial route is a base that routes build on without affecting each other:

const tenant = route
	.prefix("/tenants/:tenant")
	.params(z.object({ tenant: z.string() }))
	.headers(z.object({ authorization: z.string() }))
	.error("UNAUTHORIZED", { status: 401 });

const list = tenant.get("/posts").handler(() => listPosts()); // GET /tenants/:tenant/posts

const get = tenant
	.get("/posts/:id") // GET /tenants/:tenant/posts/:id
	.params(z.object({ id: z.coerce.number() })) // params: { tenant, id }
	.handler(({ params }) => findPost(params.tenant, params.id));
  • .prefix() comes before the method, and several prefixes join in order. Clients and OpenAPI see the full path.
  • .params(), .query(), .headers() and .body() can repeat. Their outputs merge, so each has to output an object, and a strict schema such as z.strictObject() rejects the other schema’s keys.
  • Once a route has a .params() schema, its schemas have to cover every :name segment, the prefix’s included.
  • .use() middleware runs in the order it’s added.
  • .meta() values merge, and a later value for the same key wins.
  • A method is chosen once per route, and each .response() status and .error() code is defined once. Adding the same error definition again, such as on a base and a route, is fine.

Handler Arguments

type HandlerArgs = {
	/** The validated request. */
	params: Params;
	query: Query;
	headers: Headers;
	body: Body;
	/** Values from the host and from middleware. See Middleware. */
	context: Context;
	/** The route's definition: `method`, `path` and `meta`. */
	route: RouteDefinition;
	/** The route's defined errors, to throw. */
	errors: Errors;
	/** Builds a response with a status, headers or cookies. */
	respond: Respond;
	/** Aborts when the client disconnects. */
	signal: AbortSignal;
};

The native request isn’t passed. To use it, put it in the context.

A route’s definition is also readable outside handlers, from get["~restrpc"]. Its path is undefined until the route tree is served or given to a client, when routes without a path get theirs from their keys.

Type Helpers

Write a handler or service apart from its route by inferring types from the route before .handler():

import { 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
, type
type InferServerHandler<T extends HandlerTree> = T extends {
    readonly "~restrpc": infer TRoute extends RouteDefinition;
} ? RouteHandler<Extract<Merge<Omit<TRoute, "handler" | "context" | "initialContext">>, RouteDefinition>, ContextOf<TRoute>> : { [K in keyof T as T[K] extends HandlerTree ? K : never]: InferServerHandler<Extract<T[K], HandlerTree>>; }
Infers the handler signature for a route definition.
@remarksUse a route defined without `.handler()` to write its handler separately. Pass a route tree or a contract implementer to infer a matching tree of handler types. The context is the one selected with `$context()`, or `DefaultContext` for contract routes passed directly.@see{@link https://rest-rpc.vercel.app/docs/route-builder#type-helpers}
InferServerHandler
} from "@rest-rpc/server";
import * as import zz from "zod"; const
const postSchema: z.ZodObject<{
    id: z.ZodString;
    title: z.ZodString;
    body: z.ZodString;
}, z.core.$strip>
postSchema
= import zz.
function object<{
    id: z.ZodString;
    title: z.ZodString;
    body: z.ZodString;
}>(shape?: {
    id: z.ZodString;
    title: z.ZodString;
    body: z.ZodString;
} | undefined, params?: string | {
    error?: string | z.core.$ZodErrorMap<NonNullable<z.core.$ZodIssueInvalidType<unknown> | z.core.$ZodIssueUnrecognizedKeys>> | undefined;
    message?: string | undefined | undefined;
} | undefined): z.ZodObject<{
    id: z.ZodString;
    title: z.ZodString;
    body: z.ZodString;
}, z.core.$strip>
object
({
id: z.ZodStringid: import zz.function string(params?: string | z.core.$ZodStringParams): z.ZodString (+1 overload)string(), title: z.ZodStringtitle: import zz.function string(params?: string | z.core.$ZodStringParams): z.ZodString (+1 overload)string(), body: z.ZodStringbody: import zz.function string(params?: string | z.core.$ZodStringParams): z.ZodString (+1 overload)string(), }); const
const getDefinition: Omit<ServerRouteBuilder<WithError<WithResponse<WithRequest<WithHttpMethod<RootBuilderState, "GET", "/posts/:id">, "params", z.ZodObject<{
    id: z.ZodString;
}, z.core.$strip>>, {
    body: z.ZodObject<{
        id: z.ZodString;
        title: z.ZodString;
        body: z.ZodString;
    }, z.core.$strip>;
}, undefined>, RouteErrorClassFor<"POST_NOT_FOUND", {
    readonly status: 404;
}>>, DefaultContext, DefaultContext>, "static" | OmittedMethods<...>>
getDefinition
= 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/:id">(path?: "/posts/:id" | undefined): Omit<ServerRouteBuilder<WithHttpMethod<RootBuilderState, "GET", "/posts/:id">, DefaultContext, DefaultContext>, "static" | OmittedMethods<WithHttpMethod<RootBuilderState, "GET", TPath>>>
Defines a GET route.
@see{@link https://rest-rpc.vercel.app/docs/route-builder}
get
("/posts/:id")
.
params<z.ZodObject<{
    id: z.ZodString;
}, z.core.$strip>>(schema: z.ZodObject<{
    id: z.ZodString;
}, z.core.$strip>): Omit<ServerRouteBuilder<WithRequest<WithHttpMethod<RootBuilderState, "GET", "/posts/:id">, "params", z.ZodObject<{
    id: z.ZodString;
}, z.core.$strip>>, DefaultContext, DefaultContext>, "static" | OmittedMethods<WithRequest<WithHttpMethod<RootBuilderState, "GET", "/posts/:id">, "params", TSchema>>>
Defines path parameters.
@see{@link https://rest-rpc.vercel.app/docs/route-builder#request}
params
(import zz.
function object<{
    id: z.ZodString;
}>(shape?: {
    id: z.ZodString;
} | undefined, params?: string | {
    error?: string | z.core.$ZodErrorMap<NonNullable<z.core.$ZodIssueInvalidType<unknown> | z.core.$ZodIssueUnrecognizedKeys>> | undefined;
    message?: string | undefined | undefined;
} | undefined): z.ZodObject<{
    id: z.ZodString;
}, z.core.$strip>
object
({ id: z.ZodStringid: import zz.function string(params?: string | z.core.$ZodStringParams): z.ZodString (+1 overload)string() }))
.
response<z.ZodObject<{
    id: z.ZodString;
    title: z.ZodString;
    body: z.ZodString;
}, z.core.$strip>, undefined>(schema: z.ZodObject<{
    id: z.ZodString;
    title: z.ZodString;
    body: z.ZodString;
}, z.core.$strip>, options?: undefined): Omit<ServerRouteBuilder<WithResponse<WithRequest<WithHttpMethod<RootBuilderState, "GET", "/posts/:id">, "params", z.ZodObject<{
    id: z.ZodString;
}, z.core.$strip>>, {
    body: z.ZodObject<{
        id: z.ZodString;
        title: z.ZodString;
        body: z.ZodString;
    }, 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
(
const postSchema: z.ZodObject<{
    id: z.ZodString;
    title: z.ZodString;
    body: z.ZodString;
}, z.core.$strip>
postSchema
)
.
error<"POST_NOT_FOUND", {
    readonly status: 404;
}>(code: "POST_NOT_FOUND", options?: {
    readonly status: 404;
} | undefined): Omit<ServerRouteBuilder<WithError<WithResponse<WithRequest<WithHttpMethod<RootBuilderState, "GET", "/posts/:id">, "params", z.ZodObject<{
    id: z.ZodString;
}, z.core.$strip>>, {
    body: z.ZodObject<{
        id: z.ZodString;
        title: z.ZodString;
        body: z.ZodString;
    }, z.core.$strip>;
}, undefined>, RouteErrorClassFor<"POST_NOT_FOUND", {
    readonly status: 404;
}>>, DefaultContext, DefaultContext>, "static" | OmittedMethods<...>> (+1 overload)
Adds an error, the same as adding `routeError(code, options)`. The status defaults to 400.
@see{@link https://rest-rpc.vercel.app/docs/errors#define-and-throw}
error
("POST_NOT_FOUND", { status: 404status: 404 });
const
const getPost: RouteHandler<{
    readonly metaShape?: DefaultMeta | undefined;
    readonly method: "GET";
    readonly path: "/posts/:id";
    request: {
        params: readonly [z.ZodObject<{
            id: z.ZodString;
        }, z.core.$strip>];
    };
    responses: {
        200: {
            body: z.ZodObject<{
                id: z.ZodString;
                title: z.ZodString;
                body: z.ZodString;
            }, z.core.$strip>;
        };
    };
    errors: {
        POST_NOT_FOUND: RouteErrorClassFor<"POST_NOT_FOUND", {
            readonly status: 404;
        }>;
    };
}, DefaultContext>
getPost
:
type InferServerHandler<T extends HandlerTree> = T extends {
    readonly "~restrpc": infer TRoute extends RouteDefinition;
} ? RouteHandler<Extract<Merge<Omit<TRoute, "handler" | "context" | "initialContext">>, RouteDefinition>, ContextOf<TRoute>> : { [K in keyof T as T[K] extends HandlerTree ? K : never]: InferServerHandler<Extract<T[K], HandlerTree>>; }
Infers the handler signature for a route definition.
@remarksUse a route defined without `.handler()` to write its handler separately. Pass a route tree or a contract implementer to infer a matching tree of handler types. The context is the one selected with `$context()`, or `DefaultContext` for contract routes passed directly.@see{@link https://rest-rpc.vercel.app/docs/route-builder#type-helpers}
InferServerHandler
<typeof
const getDefinition: Omit<ServerRouteBuilder<WithError<WithResponse<WithRequest<WithHttpMethod<RootBuilderState, "GET", "/posts/:id">, "params", z.ZodObject<{
    id: z.ZodString;
}, z.core.$strip>>, {
    body: z.ZodObject<{
        id: z.ZodString;
        title: z.ZodString;
        body: z.ZodString;
    }, z.core.$strip>;
}, undefined>, RouteErrorClassFor<"POST_NOT_FOUND", {
    readonly status: 404;
}>>, DefaultContext, DefaultContext>, "static" | OmittedMethods<...>>
getDefinition
> = ({
params: {
    id: string;
}
params
,
errors: {
    POST_NOT_FOUND: (options?: {
        message?: string | undefined;
        cookies?: readonly string[] | undefined;
        cause?: unknown;
        data?: undefined;
        headers?: undefined;
    } | undefined) => RouteError<"POST_NOT_FOUND", undefined, 404, Record<string, unknown>>;
}
errors
,
}) => { if (
params: {
    id: string;
}
params
.id: stringid !== "post_1") throw
errors: {
    POST_NOT_FOUND: (options?: {
        message?: string | undefined;
        cookies?: readonly string[] | undefined;
        cause?: unknown;
        data?: undefined;
        headers?: undefined;
    } | undefined) => RouteError<"POST_NOT_FOUND", undefined, 404, Record<string, unknown>>;
}
errors
.
type POST_NOT_FOUND: (options?: {
    message?: string | undefined;
    cookies?: readonly string[] | undefined;
    cause?: unknown;
    data?: undefined;
    headers?: undefined;
} | undefined) => RouteError<"POST_NOT_FOUND", undefined, 404, Record<string, unknown>>
POST_NOT_FOUND
();
return { id: stringid:
params: {
    id: string;
}
params
.id: "post_1"id, title: stringtitle: "Hello", body: stringbody: "First post" };
}; const
const get: HandledRoute<{
    readonly method: "GET";
    readonly path: "/posts/:id";
    request: {
        params: readonly [z.ZodObject<{
            id: z.ZodString;
        }, z.core.$strip>];
    };
    responses: {
        200: {
            body: z.ZodObject<{
                id: z.ZodString;
                title: z.ZodString;
                body: z.ZodString;
            }, z.core.$strip>;
        };
    };
    errors: {
        POST_NOT_FOUND: RouteErrorClassFor<"POST_NOT_FOUND", {
            readonly status: 404;
        }>;
    };
    readonly metaShape?: DefaultMeta | undefined;
}, DefaultContext, DefaultContext, HandlerResult<{
    readonly metaShape?: DefaultMeta | undefined;
    readonly method: "GET";
    readonly path: "/posts/:id";
    request: {
        params: readonly [z.ZodObject<{
            id: z.ZodString;
        }, z.core.$strip>];
    };
    responses: {
        200: {
            body: z.ZodObject<{
                id: z.ZodString;
                title: z.ZodString;
                body: z.ZodString;
            }, z.core.$strip>;
        };
    };
    errors: {
        POST_NOT_FOUND: RouteErrorClassFor<"POST_NOT_FOUND", {
            readonly status: 404;
        }>;
    };
}>>
get
=
const getDefinition: Omit<ServerRouteBuilder<WithError<WithResponse<WithRequest<WithHttpMethod<RootBuilderState, "GET", "/posts/:id">, "params", z.ZodObject<{
    id: z.ZodString;
}, z.core.$strip>>, {
    body: z.ZodObject<{
        id: z.ZodString;
        title: z.ZodString;
        body: z.ZodString;
    }, z.core.$strip>;
}, undefined>, RouteErrorClassFor<"POST_NOT_FOUND", {
    readonly status: 404;
}>>, DefaultContext, DefaultContext>, "static" | OmittedMethods<...>>
getDefinition
.
handler<HandlerResult<{
    readonly metaShape?: DefaultMeta | undefined;
    readonly method: "GET";
    readonly path: "/posts/:id";
    request: {
        params: readonly [z.ZodObject<{
            id: z.ZodString;
        }, z.core.$strip>];
    };
    responses: {
        200: {
            body: z.ZodObject<{
                id: z.ZodString;
                title: z.ZodString;
                body: z.ZodString;
            }, z.core.$strip>;
        };
    };
    errors: {
        POST_NOT_FOUND: RouteErrorClassFor<"POST_NOT_FOUND", {
            readonly status: 404;
        }>;
    };
}>>(handler: HandlerFor<{
    readonly method: "GET";
    readonly path: "/posts/:id";
    request: {
        params: readonly [z.ZodObject<{
            id: z.ZodString;
        }, z.core.$strip>];
    };
    responses: {
        ...;
    };
    errors: {
        POST_NOT_FOUND: RouteErrorClassFor<"POST_NOT_FOUND", {
            readonly status: 404;
        }>;
    };
    readonly metaShape?: DefaultMeta | undefined;
}, DefaultContext, HandlerResult<...>>): HandledRoute<...>
Attaches the server handler that completes the route.
@see{@link https://rest-rpc.vercel.app/docs/route-builder#responses}
handler
(
const getPost: RouteHandler<{
    readonly metaShape?: DefaultMeta | undefined;
    readonly method: "GET";
    readonly path: "/posts/:id";
    request: {
        params: readonly [z.ZodObject<{
            id: z.ZodString;
        }, z.core.$strip>];
    };
    responses: {
        200: {
            body: z.ZodObject<{
                id: z.ZodString;
                title: z.ZodString;
                body: z.ZodString;
            }, z.core.$strip>;
        };
    };
    errors: {
        POST_NOT_FOUND: RouteErrorClassFor<"POST_NOT_FOUND", {
            readonly status: 404;
        }>;
    };
}, DefaultContext>
getPost
);
/** The object a handler receives, with every handler argument. */
type InferServerRequest<Route>;
/** What a handler can return for the responses `.response()` defines. */
type InferServerResponse<Route>;
/** The full handler signature. */
type InferServerHandler<Route>;

Each also takes a route tree and returns a tree of types: InferServerRequest<typeof router>["posts"]["create"].

Was this page helpful?