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

Fetch Client

Call your routes over HTTP with a typed client.

import { createClient } from "@rest-rpc/core";
import { getContract } from "./contract.ts" with { type: "macro" };

export const client = createClient(getContract(), {
	origin: "https://api.example.com",
});

The client has the same shape as the route tree. In a browser app on the same origin as the API, no options are needed.

Call Routes

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

if (response.status === 200) {
	console.log(response.body.title);
}

A call resolves with one of the route’s successful responses:

type Result = {
	/** Checking it narrows `body` and `headers` to that response. */
	status: number;
	/** `undefined` for a response without a body. */
	body: Body;
	/** Lowercase names. Defined headers are typed. */
	headers: Record<string, string>;
	/** `Set-Cookie` values. Always empty in browsers. */
	cookies: readonly string[];
};

Anything else rejects. See Errors for handling them typed, and Server-Sent Events for streams.

Per-Call Options

The second argument takes Fetch options and headers the route doesn’t define:

const response = await client.posts.get(
	{ params: { id: "post_1" } },
	{
		cache: "no-store",
		signal: controller.signal,
		additionalHeaders: { "x-trace-id": traceId },
	},
);

await client.health(undefined, { cache: "no-store" }); // a route without input

When a header is set in several places, the route’s headers win over additionalHeaders, which win over globalHeaders.

Client Options

type CreateClientOptions = {
	/**
	 * The server's origin, such as `https://api.example.com`, without a path.
	 * Defaults to the page's origin in browsers. Required elsewhere.
	 */
	origin?: string;
	/** The path the routes are served under, the same as the server's. */
	mountPath?: `/${string}`;
	/**
	 * Headers added to every request: values, promises, or functions called
	 * for each request. Route headers they always set become optional in calls.
	 */
	globalHeaders?: ClientHeaders;
	/** Functions around each request. See Interceptors. */
	interceptors?: readonly ClientInterceptor[];
	/** Fetch options for every request. Per-call options override them. */
	fetchOptions?: Omit<FetchOptions, "signal" | "additionalHeaders">;
	/** Sends each request. Defaults to the global `fetch`. */
	fetch?: (request: Request, init?: RequestInit) => Promise<Response>;
	/** Codecs for other body formats, the same as the server's. */
	bodyCodecs?: readonly BodyCodec[];
	/** Event data format, the same as the server's. */
	sse?: { format?: SseFormat };
	/** Validates responses with the contract's schemas. `false` by default. */
	validateResponses?: boolean;
};
const client = createClient(getContract(), {
	origin: "https://api.example.com",
	globalHeaders: {
		authorization: () => `Bearer ${readToken()}`,
	},
	fetchOptions: { credentials: "include" },
});

Custom Fetch

Any function that takes a Request works. Pass an app’s fetch to call it in the same process, such as in tests:

const client = createClient(router, {
	origin: "http://localhost",
	fetch: app.fetch,
});

Interceptors

An interceptor wraps each request, for logging, retries or refreshing credentials:

import { clientInterceptor, createClient } from "@rest-rpc/core";

const refreshOn401 = clientInterceptor(async ({ request, next, route }) => {
	const response = await next(request.clone()); // a body can only be sent once
	if (response.status !== 401 || route.meta?.access === "public") {
		return response;
	}
	await refreshToken();
	request.headers.set("authorization", `Bearer ${readToken()}`);
	return next(request);
});

const timeout = (ms: number) =>
	clientInterceptor(({ request, next }) =>
		next(
			new Request(request, {
				signal: AbortSignal.any([request.signal, AbortSignal.timeout(ms)]),
			}),
		),
	);

const client = createClient(getContract(), {
	interceptors: [refreshOn401, timeout(10_000)],
});
  • Interceptors run in order, the first outermost.
  • next() sends the request, or another one you pass, and can be called more than once.
  • route is the called route’s definition, with its metadata.
  • They see error responses too, since they run before the response is read.

Response Validation

With a shared contract, the client can validate response bodies, headers and stream events with the contract’s schemas:

const client = createClient(contract, { validateResponses: true });
  • A response that fails validation rejects with an Error.
  • It has no effect on an extracted contract, which has no schemas.

Type Helpers

import type { InferClientRequest, InferClientResponse } from "@rest-rpc/core";

type UpdatePostRequest = InferClientRequest<typeof client.posts.update>;
type GetPostResponse = InferClientResponse<typeof client.posts.get>;
/** What a call takes, or `undefined` for a route without input. */
type InferClientRequest<Route, GlobalHeaders>;
/** Every response a call resolves with. */
type InferClientResponse<Route>;
/** The route's defined errors. */
type InferClientError<Route>;
/** The `data` of each event of a stream. */
type InferClientStreamData<Route>;
/** The type of a whole client. */
type ClientFor<Router>;
  • Each takes a client route, a route, or a whole tree, which returns a tree of types: InferClientResponse<typeof client>["posts"]["get"].
  • For a route rather than a client, pass typeof globalHeaders as InferClientRequest’s second argument to make the headers it sets optional.

Was this page helpful?