oRPC Adapter
The Hyper Fetch oRPC Adapter connects Hyper Fetch to an oRPC server, so procedures get caching, queueing, offline support and React hooks, with types inferred from your router.
- Call oRPC procedures with the same request API you use for REST and GraphQL.
- Infer types from your router or contract through the regular
createSdk. - Keep rich types such as
Date,BigInt,Map,Setand files, encoded by the oRPC serializer. - Cache every input separately, without writing query keys by hand.
Installation
Install the adapter next to the core package and @orpc/client. The adapter encodes the data with the oRPC serializer
from @orpc/client, so the client and the server always speak the same format. @orpc/server is only needed for the
OrpcSchema type, and the project that imports your router type usually has it already.
npm install @hyper-fetch/core @hyper-fetch/orpc @orpc/client
Getting Started
Point the client at the URL where your RPCHandler is mounted, and describe the router with OrpcSchema.
import { createClient, createSdk } from "@hyper-fetch/core";
import { OrpcAdapter } from "@hyper-fetch/orpc";
import type { OrpcSchema } from "@hyper-fetch/orpc";
import type { router } from "./server";
const client = createClient({ url: "http://localhost:3000/rpc" }).setAdapter(OrpcAdapter());
const api = createSdk<typeof client, OrpcSchema<typeof router>>(client, { camelCaseToKebabCase: false });
const { data, error } = await api.planet.find.$query.setPayload({ id: 1 }).send();
camelCaseToKebabCase: false keeps procedure names as they are written in the router (findById, not find-by-id).
Contract-first
For contract-first APIs, pass the client type of the contract. It works without @orpc/server.
import type { ContractRouterClient } from "@orpc/contract";
import type { contract } from "./contract";
const api = createSdk<typeof client, OrpcSchema<ContractRouterClient<typeof contract>>>(client, {
camelCaseToKebabCase: false,
});
OrpcSchema<RouterClient<typeof router>> works the same way, so you can reuse the client type you already have.
Queries and mutations
oRPC procedures have no kind, so every procedure is available both as $query and $mutation, the same way the oRPC
query utils offer queryOptions and mutationOptions for every procedure. The procedure input is the request payload.
import { useFetch, useSubmit } from "@hyper-fetch/react";
const { data, loading } = useFetch(api.planet.find.$query.setPayload({ id: 1 }));
const { submit } = useSubmit(api.planet.create.$mutation);
await submit({ payload: { name: "Earth" } });
Like GET requests in the HttpAdapter, identical queries running at the same time are deduplicated by default.
Mutations are not deduplicated.
Both are sent as POST {url}/planet/find with the serialized input as a JSON body, which is what the oRPC RPCHandler
accepts by default.
GET queries
Set queryMethod: "GET" to send queries as GET {url}/planet/find?data={"json":{"id":1}}, which lets the browser,
proxies and CDNs cache them. Mutations always use POST.
const client = createClient({ url: "http://localhost:3000/rpc" }).setAdapter(OrpcAdapter({ queryMethod: "GET" }));
// Use POST for one request
const { data } = await api.planet.list.$query.setOptions({ queryMethod: "POST" }).send();
The RPCHandler accepts GET only for the procedures declared with .route({ method: "GET" }), unless its
strictGetMethodPluginEnabled option is turned off. Other procedures fail with METHOD_NOT_SUPPORTED and the status
405. Requests with files, or with a URL longer than 2083 characters, are sent with POST, the same as in the official
RPCLink.
Requests without the SDK
The SDK is optional. QUERY and MUTATION are the methods of this adapter, and the endpoint is the procedure path.
const findPlanet = client.createRequest<{ response: Planet; payload: { id: number } }>()({
endpoint: "planet/find",
method: "QUERY",
});
const createPlanet = client.createRequest<{ response: Planet; payload: { name: string } }>()({
endpoint: "planet/create",
method: "MUTATION",
});
QUERY is the default method. The paths planet/find and /planet/find point to the same procedure and share the
cache.
Cache keys
The adapter adds the serialized input to the cache and query keys, so { id: 1 } and { id: 2 } are cached,
deduplicated and queued separately. A Date and its ISO string stay different keys. Files are compared by their name,
type and size. The abort key does not contain the input, so request.abort() stops every running call of the procedure.
A cancelable request replaces the running call with the same query key, which means the same input. To cancel the
previous call when the input changes, for example in a search field, share the query key between the inputs.
const search = api.planet.search.$query.setCancelable(true).setDeduplicate(false).setQueryKey("planet-search");
Errors
Failed procedures resolve with the error sent by the server, in the shape of ORPCError.toJSON(), and the HTTP status
of the response.
const { error, status } = await api.planet.find.$query.setPayload({ id: 999 }).send();
status; // 404
error?.defined; // true for the errors from the `.errors()` map of the procedure
error?.code; // "NOT_FOUND"
error?.status; // 404
error?.message; // "Planet not found"
error?.data; // { id: 999 }
With OrpcSchema the defined errors keep their code and data type, so checking error.defined and error.code narrows
error.data. Any other error has defined: false, and its data is unknown. For requests created by hand, use the
exported OrpcErrorType.
A response that did not come from a procedure, such as an HTML error page from a proxy, resolves with an
UnexpectedError and the status of that response.
Rich types and files
The input and the output go through the oRPC serializer, so these types arrive as they were sent: Date, BigInt,
Map, Set, URL, RegExp, NaN and undefined inside arrays. Object properties set to undefined are left out,
the same as in JSON.
const { data } = await api.event.byDate.$query.setPayload({ date: new Date() }).send();
data?.createdAt; // Date
An input with a File or a Blob is sent as multipart/form-data, and outputs with files are read the same way.
await api.planet.uploadImage.$mutation.setPayload({ planetId: 1, image: file }).send();
Custom types need the same customJsonSerializers on the server and in the adapter.
const client = createClient({ url }).setAdapter(OrpcAdapter({ customJsonSerializers: [moneySerializer] }));
Options
Request options are passed to fetch, with an additional timeout in milliseconds (5 seconds by default) and
queryMethod.
const findPlanet = client.createRequest<{ response: Planet }>()({
endpoint: "planet/me",
options: { credentials: "include", timeout: 10000 },
});
Query params are appended to the URL. The data key is reserved for the oRPC format and is skipped.
Limitations
- Event iterators and request batching are not supported. Procedures returning an event iterator are left out of
OrpcSchema. - The SDK can't reach a procedure named like a request property, such as
sendormethod. UsecreateRequestwith the procedure path for those.
OrpcAdaptercalls oRPC procedures with the RPC protocol, andOrpcSchematypes them throughcreateSdk.- Every procedure is available as
$queryand$mutation, sent withPOSTor, for queries, withGET. - The oRPC serializer keeps
Date,BigInt, files and other rich types. - Errors keep the
ORPCErrorshape, and defined errors are typed by code.

