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

Quickstart

Define routes, serve them, and call them from a typed client.

This builds two routes with Bun and Zod. The same code runs on Deno and Cloudflare Workers, and Node with a different import.

npm install @rest-rpc/core @rest-rpc/server zod
pnpm add @rest-rpc/core @rest-rpc/server zod
yarn add @rest-rpc/core @rest-rpc/server zod
bun add @rest-rpc/core @rest-rpc/server zod
nub add @rest-rpc/core @rest-rpc/server zod
aube add @rest-rpc/core @rest-rpc/server zod

Define Routes

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

type Post = { id: string; title: string; body: string };
const posts = new Map<string, Post>();

// POST /posts/create
const create = route
	.body(z.object({ title: z.string().min(1), body: z.string() }))
	.handler(({ body: { title, body } }) => {
		const post: Post = { id: crypto.randomUUID(), title, body };
		posts.set(post.id, post);
		return post;
	});

// GET /posts/:id?preview=true
const get = route
	.get("/posts/:id")
	.params(z.object({ id: z.string() }))
	.query(z.object({ preview: z.enum(["true", "false"]).optional() }))
	.error("POST_NOT_FOUND", { status: 404 })
	.handler(({ params, query, errors }) => {
		const post = posts.get(params.id);
		if (!post) throw errors.POST_NOT_FOUND();
		return {
			...post,
			body: query.preview === "true" ? post.body.slice(0, 40) : post.body,
		};
	});

export const router = { posts: { create, get } };

The schemas validate requests, and what the handler returns is what the client receives, typed.

Serve Them

import { createApp } from "@rest-rpc/server";
import { router } from "./router.ts";

export default createApp(router);

Run bun server.ts to serve it on port 3000.

Call Them

The client needs the routes’ types and paths, but not their server code. extractContract() runs as a Bun macro at build time, so only plain data ends up in the client bundle:

import { extractContract } from "@rest-rpc/core";
import { router } from "./router.ts";

export function getContract() {
	return extractContract(router);
}
import { createClient, isDefinedError, safe } from "@rest-rpc/core";
import { getContract } from "./contract.ts" with { type: "macro" };

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

const created = await client.posts.create({
	body: { title: "Hello", body: "First post" },
});
const result = await safe(
	client.posts.get({
		params: { id: created.body.id },
		query: { preview: "true" },
	}),
);

if (!result.error) {
	console.log(result.data.body.title);
} else if (
	isDefinedError(result.error) &&
	result.error.code === "POST_NOT_FOUND"
) {
	console.log(result.error.message);
}

For Vite and other bundlers, see Contract Extraction.

Next Steps

Was this page helpful?