---
title: Contract-first
description: Define routes in a shared contract, implement them on the server, and call them from the client.
---

A contract defines the HTTP interface without handlers, so clients can import
it without any server code. It uses the same builder as
[implementation-first routes](/docs/route-builder), imported from
`@rest-rpc/core`.

## Define the Contract

```ts contract.ts
import { route } from "@rest-rpc/core";
import * as z from "zod";

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

const create = route
	.body(z.object({ title: z.string().min(1), body: z.string() }))
	.response(postSchema);

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

export const contract = { posts: { create, get } };
```

- Every route needs at least one `.response()`, since there's no handler to
  infer it from. Use `sse(schema)` for a stream, and `raw()` for a returned
  Fetch `Response`.
- Metadata is part of the contract: set it with `$meta<T>()` and `.meta()`
  here.

## Implement It

`implement()` turns a contract route into a server route that needs only a
handler:

```ts server.ts
import { createApp, implement } from "@rest-rpc/server";
import { contract } from "./contract.ts";

const create = implement(contract.posts.create).handler(({ body }) =>
	createPost(body.title, body.body),
);

const get = implement(contract.posts.get).handler(({ params, errors }) => {
	const post = findPost(params.id);
	if (!post) throw errors.POST_NOT_FOUND();
	return post;
});

export default createApp({ posts: { create, get } });
```

Context and middleware belong to the server, so add them to the
`implement()` result. Pass a whole contract tree to share them with every
route in it:

```ts
const posts = implement(contract.posts)
	.$context<{ headers: Headers }>()
	.use(authenticate); // adds `user` to the context

export const router = {
	posts: {
		create: posts.create.handler(({ body, context }) =>
			createPost(body.title, body.body, context.user),
		),
		get: posts.get.handler(({ params }) => findPost(params.id)),
	},
};
```

:::error[Reserved keys]
`use` and `$context` can't be top-level keys of a contract tree passed to
`implement()`. Using them is a type error.
:::

## Call It

Pass the contract to the client as it is:

```ts client.ts
import { createClient } from "@rest-rpc/core";
import { contract } from "./contract";

const client = createClient(contract, { origin: "http://localhost:3000" });

const created = await client.posts.create({
	body: { title: "Hello", body: "First post" },
});
```

Since the contract has schemas, the client can
[validate responses](/docs/client/fetch-client#response-validation) with
them.
