tRPC procedure types and typed React hooks without code generation
Define tRPC queries, mutations, and subscriptions once on the server and consume typed React hooks on the client—no separate code generation step.
05 Mar 2026, 21:28 UTC

Start with the decision: query, mutation, or subscription
tRPC divides every endpoint into one of three procedure builders. A query is a read operation with no side effects; tRPC pairs it with React Query’s useQuery hook and caches the result. A mutation is a write operation; it maps to useMutation and runs when you call its trigger function. A subscription is a long-lived stream, usually over WebSocket, and maps to useSubscription.
The useful takeaway: define the procedure once on the server, export the router type, and import it on the client. tRPC infers input and output types for the generated hooks with no separate code generation step.
Worked example: server router and React client
This example assumes tRPC v11, @trpc/server, @trpc/react-query, and Zod for input validation.
Server: define procedures and export the router type
import { initTRPC, router } from '@trpc/server';
import { z } from 'zod';
import { superjson } from 'superjson';
const t = initTRPC.create({
transformer: superjson,
});
const appRouter = router({
getUser: t.procedure
.input(z.object({ id: z.string() }))
.query(async ({ input }) => {
return { id: input.id, name: 'Ada', updatedAt: new Date() };
}),
updateUser: t.procedure
.input(z.object({ id: z.string(), name: z.string() }))
.mutation(async ({ input }) => {
return { id: input.id, name: input.name };
}),
});
export type AppRouter = typeof appRouter;
export type AppRouter = typeof appRouter is the type contract. The client imports only the type, not the runtime value, which avoids bundling server code in the browser.
Client: create typed hooks and consume them
import { createTRPCReact, httpBatchLink } from '@trpc/react-query';
import type { AppRouter } from '@/server/router';
import { superjson } from 'superjson';
import { QueryClient } from '@tanstack/react-query';
export const trpc = createTRPCReact();
const queryClient = new QueryClient();
export function App() {
return (
);
}
function UserProfile({ userId }: { userId: string }) {
const userQuery = trpc.getUser.useQuery({ id: userId });
const updateUser = trpc.updateUser.useMutation({
onSuccess: () => {
// Mutations do not refetch related queries automatically.
trpc.getUser.invalidate({ id: userId });
},
});
if (userQuery.isLoading) return Loading…;
if (userQuery.error) return Error: {userQuery.error.message};
return (
{userQuery.data?.name}
updateUser.mutate({ id: userId, name: 'Grace' })}
disabled={updateUser.isPending}
>
Rename
);
}
Hovering over userQuery.data in TypeScript shows the inferred shape, not any. The input object { id: userId } is checked against the Zod schema at compile time and again at runtime when the request is sent.
How the mechanism works
When you call createTRPCReact(), tRPC walks the router type and generates a hook for every procedure path. getUser becomes trpc.getUser.useQuery; updateUser becomes trpc.updateUser.useMutation. The hook’s generic parameters come from the procedure’s input and output types, so there is no manual interface to maintain.
A link is the transport layer. httpBatchLink sends requests over HTTP and batches multiple calls in one tick. superjson is a transformer that preserves JavaScript types such as Date, Map, Set, and undefined across JSON serialization.
Limits and common mistakes
| Procedure | Semantic intent | Generated hook | Typical use |
|---|---|---|---|
| query | Read, cacheable | useQuery | Fetch user profile |
| mutation | Write, side effect | useMutation | Update user name |
| subscription | Streaming updates | useSubscription | Live counter or chat |
- Type inference breaks on bad imports. Importing the router value instead of
typeof appRouter, or creating a circular import between server and client, widens inputs tounknownorany. - SuperJSON must match on both ends. If the server uses
transformer: superjsonbut the client omits it,Datevalues arrive as ISO strings andundefinedfields may be dropped. - Mutations do not auto-invalidate. After
updateUsersucceeds, relatedgetUserqueries stay stale until you calltrpc.getUser.invalidate()or handle it inonSuccess. - Subscriptions need WebSocket. The default HTTP batch link cannot open a socket. You must compose
wsLinkwithsplitLinkand run a WebSocket-capable server or compatible edge runtime. - Validation errors are runtime errors. Malformed input produces a
TRPCErrorwith codeBAD_REQUEST; the React hook surfaces it througherrorunlessthrowOnErroris enabled.
Verification checklist
- Run
npx tsc --noEmitin the client package. Hover overuserQuery.dataand confirm the type is the inferred procedure output, notany. - Add a query that returns
new Date(). Confirm the client receives aDateinstance, not an ISO string, only when SuperJSON is enabled on both server and client. - Temporarily change the client import to the router value instead of the type. Observe TypeScript widening procedure inputs to
unknown, then revert. - For subscriptions, open browser DevTools, filter WebSocket frames, and confirm updates arrive and stop after the component unmounts.
Scaffold command
# Run in the directory where you want the new project.
# No special OS permissions are required; a package registry login may be needed for private scopes.
npm create trpc@latest my-app --template next
Expected checks: the installer creates a project directory, installs dependencies, and prints a success message. Risks: network failure during install or an unsupported Node version.
Version note
This guide targets tRPC v11 with @trpc/react-query. Procedure APIs and link names can change between major versions; check your installed package’s type exports before copying the import paths.
This is a configuration and type-checking exercise, not a database migration, so no rollback procedure is required. If you change the router type, revert the import and re-run the type check.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.