---
title: Route Builder
description: 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

```ts
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

```ts
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

```ts
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](/docs/http-behavior/encoding#params-query-and-headers).
- `.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:

```ts
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](/docs/server-sent-events).
- A Fetch `Response`: sent as it is. See [Raw Responses](#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](/docs/errors).

### Inferred Responses

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

:::note
A value built in a variable before it's returned loses literal types such as
`"draft"`. Use `as const` or an annotation to keep them.
:::

### Defined Responses

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

```ts
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:

```ts
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](/docs/contract-first), 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:

```ts
route.get("/health").static({ ok: true });
route
	.get("/robots.txt")
	.static(
		respond("User-agent: *", { headers: { "content-type": "text/plain" } }),
	);
```

:::warning
Static routes skip middleware and interceptors, so use them only for public
content. Put headers such as CORS in the response itself.
:::

- 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:

```ts
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

```ts
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](/docs/middleware#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()`:

```ts twoslash
import { route, type InferServerHandler } from "@rest-rpc/server";
import * as z from "zod";

const postSchema = z.object({
	id: z.string(),
	title: z.string(),
	body: z.string(),
});

const getDefinition = route
	.get("/posts/:id")
	.params(z.object({ id: z.string() }))
	.response(postSchema)
	.error("POST_NOT_FOUND", { status: 404 });

const getPost: InferServerHandler<typeof getDefinition> = ({
	params,
	errors,
}) => {
	if (params.id !== "post_1") throw errors.POST_NOT_FOUND();
	return { id: params.id, title: "Hello", body: "First post" };
};

const get = getDefinition.handler(getPost);
```

```ts
/** 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"]`.
