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

Contract-first

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, imported from @rest-rpc/core.

Define the Contract

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:

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:

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)),
	},
};

Call It

Pass the contract to the client as it is:

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 with them.

Was this page helpful?