oRPC
A list of planets with a form to add one. The API is described by an oRPC contract first, the server implements it, and
the React client gets its types from the contract alone. Dates travel as real Date objects, and a duplicate name comes
back as a typed error.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { useFetch, useSubmit } from "@hyper-fetch/react";
import { type FormEvent, useState } from "react";
import { sdk } from "./api";
const types = ["rocky", "gas", "ice"] as const;
export const App = () => {
const [name, setName] = useState("");
const [type, setType] = useState<(typeof types)[number]>("ice");
const [date, setDate] = useState("1930-02-18");
const { data, error, loading, refetch } = useFetch(sdk.planet.list.$query);
const { submit, submitting, error: createError, onSubmitSuccess } = useSubmit(sdk.planet.create.$mutation);
onSubmitSuccess(() => {
setName("");
refetch();
});
const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
// `discoveredAt` is a Date. The adapter encodes it with the oRPC serializer.
submit({ payload: { name, type, discoveredAt: new Date(date) } });
};
// Network failures are plain `Error`s. For procedure errors, `defined` and `code` narrow `data` to the contract type.
const isProcedureError = createError && "defined" in createError;
const conflict =
isProcedureError && createError.defined && createError.code === "CONFLICT" ? createError.data.name : null;
return (
<main className="container">
<hgroup>
<h1>oRPC planets</h1>
<p>A contract-first oRPC API on Hono, called through HyperFetch with types from the contract.</p>
</hgroup>
<form onSubmit={handleSubmit}>
<fieldset className="grid">
<input value={name} onChange={(event) => setName(event.target.value)} placeholder="Name, e.g. Pluto" />
<select
value={type}
onChange={(event) => setType(types.find((item) => item === event.target.value) ?? "rocky")}
>
{types.map((item) => (
<option key={item}>{item}</option>
))}
</select>
<input type="date" value={date} onChange={(event) => setDate(event.target.value)} required />
<button type="submit" aria-busy={submitting} disabled={submitting}>
Add planet
</button>
</fieldset>
{conflict && <small className="error">{conflict} is already on the list.</small>}
{createError && !conflict && <small className="error">{createError.message}</small>}
</form>
{loading && !data && <p aria-busy="true">Loading planets...</p>}
{error && <p className="error">Could not load planets: {error.message}</p>}
<table>
<thead>
<tr>
<th>Planet</th>
<th>Type</th>
<th>Discovered</th>
</tr>
</thead>
<tbody>
{data?.map((planet) => (
<tr key={planet.id}>
<td>{planet.name}</td>
<td>{planet.type}</td>
{/* No parsing: `discoveredAt` arrives as a Date. */}
<td>
{planet.discoveredAt.toLocaleDateString(undefined, {
dateStyle: "long",
})}
</td>
</tr>
))}
</tbody>
</table>
</main>
);
};
npx tiged BetterTyped/hyper-fetch/examples/orpc/basic hyper-fetch-orpc-basic && cd hyper-fetch-orpc-basic && npm install && npm run dev- Contract-first:
OrpcSchema<ContractRouterClient<typeof contract>>types the SDK without importing the server. OrpcAdaptersends every procedure in the oRPC RPC format, so the server'sRPCHandlerunderstands it.- Rich types:
discoveredAtis aDatein the input and in the output, encoded by the oRPC serializer. - Defined errors: the
CONFLICTerror from the contract keeps its code anddatatype on the client.
How it works
-
server/contract.tsdeclaresplanet.listandplanet.createwithocfrom@orpc/contract: zod schemas for the input and output, and an.errors()map withCONFLICT. -
server/router.tsimplements the contract withimplement(contract). A handler that returns the wrong shape or throws an undeclared error does not compile. -
server/app.tsmounts the router with the fetchRPCHandlerunder/api/rpcin Hono.vite.config.tsruns that app for/apirequests, so onenpm run devstarts both sides. -
src/api.tssetsOrpcAdapter()on the client and builds the SDK from the contract type:createSdk<typeof client, OrpcSchema<ContractRouterClient<typeof contract>>>(client, { camelCaseToKebabCase: false });oRPC procedures have no query or mutation kind, so each one offers both
$queryand$mutation.Appuses$queryfor the list, which is deduplicated like aGET, and$mutationfor the create, which never is. -
Appreads the list withuseFetch(sdk.planet.list.$query)and rendersplanet.discoveredAt.toLocaleDateString()with no parsing. The form sendsdiscoveredAt: new Date(date)throughuseSubmit. -
Add a planet that is already listed. The server throws
errors.CONFLICT({ data: { name } }). On the client,"defined" in errorrules out network failures, anderror.defined && error.code === "CONFLICT"narrowserror.datato{ name: string }.
- You design the API as a contract first and want the frontend to start before the backend is done.
- You need
Date,BigInt,Map,Setor files to survive the trip without manual parsing. - With a router instead of a contract, use
OrpcSchema<typeof router>. The rest of the code stays the same.
Related
OrpcAdapter speaks the oRPC protocol and OrpcSchema reads a contract or router type, so createSdk gives you typed
requests for every procedure. Dates and defined errors keep their types from the server to the component.
