---
title: Contract Extraction
description: 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](/docs/contract-first), skip this page.

## With a Macro

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

export function getContract() {
	return extractContract(router);
}
```

```ts client.ts
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`](https://github.com/unplugin/unplugin-macros):

```ts vite.config.ts
import Macros from "unplugin-macros/vite";
import { defineConfig } from "vite";

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

:::note
The macro runs in Node or Bun, not the bundler, so path aliases don't apply
to it or to what `contract.ts` imports. Write relative imports with their
`.ts` extension, and enable `allowImportingTsExtensions` in the client's
`tsconfig.json`.
:::

## Without a Macro

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

```ts scripts/extract-contract.ts
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)));
```

```json package.json
{
	"scripts": {
		"contract": "node --watch scripts/extract-contract.ts",
		"dev": "npm run contract & next dev"
	}
}
```

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

:::warning[Extraction imports your server code]
The build imports `router.ts` and everything it imports. A module that throws
on import, such as one that checks environment variables, fails the build. One
that opens a database connection or a timer keeps it from finishing. Create
such services in the server and pass them as
[context](/docs/middleware#context).
:::

- 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](/docs/contract-first) if you need either.
