Skip to main content

tRPC

A todo list backed by a tRPC router. The router runs inside the Vite dev server through Hono, and the React app calls its queries and mutations with useFetch and useSubmit. Every input, output and error type comes from the router.

intermediatetrpccreateSdkuseFetchuseSubmitinvalidation
import { useFetch, useSubmit } from "@hyper-fetch/react";
import { type FormEvent, useState } from "react";

import { client, sdk, todoListsKey } from "./api";

const filters = ["all", "open", "done"] as const;

export const App = () => {
const [status, setStatus] = useState<(typeof filters)[number]>("all");
const [title, setTitle] = useState("");

// The input is the payload. Each filter is cached on its own, so switching back is instant.
const { data, error, loading } = useFetch(sdk.todos.list.$query.setPayload({ status }));
const add = useSubmit(sdk.todos.add.$mutation);
const toggle = useSubmit(sdk.todos.toggle.$mutation);

// A change affects every filter, so invalidate all cached inputs of `todos.list` at once.
const refreshLists = () => client.cache.invalidate(todoListsKey);
add.onSubmitSuccess(() => {
setTitle("");
refreshLists();
});
toggle.onSubmitSuccess(refreshLists);

const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
add.submit({ payload: { title } });
};

// Procedure errors carry `data` with the router's `errorFormatter` fields. Network failures are plain `Error`s.
const titleError = add.error && "data" in add.error ? add.error.data.fieldErrors?.title : undefined;

return (
<main className="container">
<hgroup>
<h1>tRPC todos</h1>
<p>A tRPC router served by Hono, called through HyperFetch with types inferred from the router.</p>
</hgroup>
<form onSubmit={handleSubmit}>
<fieldset role="group">
<input
value={title}
onChange={(event) => setTitle(event.target.value)}
placeholder="New todo"
aria-invalid={titleError ? true : undefined}
/>
<button type="submit" aria-busy={add.submitting} disabled={add.submitting}>
Add
</button>
</fieldset>
{add.error && <small className="error">{titleError ?? add.error.message}</small>}
</form>
<article>
<header className="toolbar">
<div role="group">
{filters.map((filter) => (
<button
key={filter}
type="button"
className={filter === status ? undefined : "outline"}
onClick={() => setStatus(filter)}
>
{filter}
</button>
))}
</div>
{/* A visited filter renders from the cache with no request, until a mutation invalidates it. */}
<small className="muted" aria-busy={loading}>
{loading ? "Fetching" : "Cached"}
</small>
</header>
{error && <p className="error">Could not load todos: {error.message}</p>}
{!data && loading && <p aria-busy="true">Loading todos...</p>}
<ul className="list">
{data?.map((todo) => (
<li key={todo.id}>
<label>
<input
type="checkbox"
checked={todo.done}
disabled={toggle.submitting}
onChange={() => toggle.submit({ payload: { id: todo.id } })}
/>
{todo.title}
</label>
</li>
))}
{data?.length === 0 && <li className="muted">Nothing here.</li>}
</ul>
</article>
</main>
);
};
Run locallynpx tiged BetterTyped/hyper-fetch/examples/trpc/basic hyper-fetch-trpc-basic && cd hyper-fetch-trpc-basic && npm install && npm run dev
What it shows
  1. TrpcAdapter sends requests in the tRPC format: queries as GET, mutations as POST.
  2. TrpcSchema<AppRouter> turns the router type into a typed SDK, with $query and $mutation for each procedure.
  3. The input is the payload, and every input has its own cache key, so each filter is cached separately.
  4. Typed errors: the router's errorFormatter adds fieldErrors, and the client sees them with their types.

How it works​

  1. server/router.ts is a regular tRPC v11 router with todos.list, todos.add and todos.toggle, validated with zod. It exports AppRouter, the only thing the client imports, and only as a type.

  2. server/app.ts mounts the router in Hono with tRPC's fetch adapter. vite.config.ts runs that Hono app for every /api request, so npm run dev starts the API and the client together:

    new Hono().all("/api/trpc/*", (c) =>
    fetchRequestHandler({
    endpoint: "/api/trpc",
    req: c.req.raw,
    router: appRouter,
    }),
    );
  3. src/api.ts points the client at /api/trpc, sets TrpcAdapter() and builds the SDK:

    const client = createClient({
    url: `${window.location.origin}/api/trpc`,
    }).setAdapter(TrpcAdapter());
    const sdk = createSdk<typeof client, TrpcSchema<AppRouter>>(client, {
    camelCaseToKebabCase: false,
    });

    camelCaseToKebabCase: false keeps the procedure names as the router spells them. sdk.todos.list.$query is a request for todos.list.

  4. App passes the procedure input as the payload: useFetch(sdk.todos.list.$query.setPayload({ status })). The adapter adds the input to the cache key, so all, open and done are three cache entries. Switch back to a filter you already opened and it renders without a request.

  5. The mutations run through useSubmit. After one succeeds, client.cache.invalidate(/^QUERY_todos\.list/) marks every cached todos.list input stale, and the mounted list fetches again.

  6. Type a title shorter than three characters. zod rejects it, the router's errorFormatter adds fieldErrors: { title: "..." }, and the form shows it. A network failure has no data, which is why the code checks "data" in add.error first.

When to use it
  • You already have a tRPC backend and want caching, queueing, offline support or HyperFetch hooks on the client.
  • One client for tRPC, REST and GraphQL, with the same request API for all of them.
  • Any server that speaks the Fetch API can host the router: Hono, Next.js route handlers, Bun, Deno or Workers.

Summary

TrpcAdapter speaks the tRPC protocol and TrpcSchema reads the router type, so createSdk gives you a typed request for every query and mutation. They work with the usual hooks and cache, keyed by the procedure input.