Skip to main content

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.

intermediateorpccreateSdktypescriptuseFetchuseSubmit
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>
);
};
Run locallynpx tiged BetterTyped/hyper-fetch/examples/orpc/basic hyper-fetch-orpc-basic && cd hyper-fetch-orpc-basic && npm install && npm run dev
What it shows
  1. Contract-first: OrpcSchema<ContractRouterClient<typeof contract>> types the SDK without importing the server.
  2. OrpcAdapter sends every procedure in the oRPC RPC format, so the server's RPCHandler understands it.
  3. Rich types: discoveredAt is a Date in the input and in the output, encoded by the oRPC serializer.
  4. Defined errors: the CONFLICT error from the contract keeps its code and data type on the client.

How it works​

  1. server/contract.ts declares planet.list and planet.create with oc from @orpc/contract: zod schemas for the input and output, and an .errors() map with CONFLICT.

  2. server/router.ts implements the contract with implement(contract). A handler that returns the wrong shape or throws an undeclared error does not compile.

  3. server/app.ts mounts the router with the fetch RPCHandler under /api/rpc in Hono. vite.config.ts runs that app for /api requests, so one npm run dev starts both sides.

  4. src/api.ts sets OrpcAdapter() 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 $query and $mutation. App uses $query for the list, which is deduplicated like a GET, and $mutation for the create, which never is.

  5. App reads the list with useFetch(sdk.planet.list.$query) and renders planet.discoveredAt.toLocaleDateString() with no parsing. The form sends discoveredAt: new Date(date) through useSubmit.

  6. Add a planet that is already listed. The server throws errors.CONFLICT({ data: { name } }). On the client, "defined" in error rules out network failures, and error.defined && error.code === "CONFLICT" narrows error.data to { name: string }.

When to use it
  • You design the API as a contract first and want the frontend to start before the backend is done.
  • You need Date, BigInt, Map, Set or 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.

Summary

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.