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

Contract Extraction

Give a browser client your routes' types without bundling server code.

A client needs the routes’ paths and types, but a browser bundle shouldn’t include server code. extractContract() reduces the routes to plain data at build time. With a shared contract, skip this page.

With a Macro

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

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

export const client = createClient(getContract());

Bun runs macros natively. For Vite, esbuild, Rolldown, Rollup, webpack or Rspack, add unplugin-macros:

import Macros from "unplugin-macros/vite";
import { defineConfig } from "vite";

export default defineConfig({
	plugins: [Macros()],
});

Without a Macro

For bundlers without macros, such as Turbopack, write the contract to a JSON file in watch mode:

import { writeFile } from "node:fs/promises";
import { extractContract } from "@rest-rpc/core";
import { router } from "../router.ts";

await writeFile("contract.json", JSON.stringify(extractContract(router)));
{
	"scripts": {
		"contract": "node --watch scripts/extract-contract.ts",
		"dev": "npm run contract & next dev"
	}
}
import { contractFromJson, createClient } from "@rest-rpc/core";
import type { router } from "./router";
import json from "./contract.json";

export const client = createClient(contractFromJson<typeof router>(json));

contractFromJson() gives the JSON the router’s type, and throws if the file isn’t an extracted contract.

Things to Know

  • The extracted contract has no schemas, so the client can’t validate responses.
  • Routes with inferred responses accept any 2xx status on the client.
  • Use a shared contract if you need either.

Was this page helpful?