trpc

v2026.09.24

tRPC v11 end-to-end type-safe APIs for TypeScript. Covers router and procedure definitions, input validation with Zod, middleware and context, subscriptions, error handling with TRPCError, React client hooks via @trpc/react-query, server-side callers with createCallerFactory, adapter setup (standalone, Express, Fastify, Hono), and testing patterns. Use when building tRPC routers, defining procedures, setting up middleware, configuring adapters, integrating tRPC with React, handling errors, implementing subscriptions, or testing tRPC procedures.

GitHub
安装命令
npx skhub add oakoss/trpc
Markdown
SKILL.md

tRPC

Overview

tRPC enables end-to-end type-safe APIs by sharing TypeScript types between server and client without code generation or schemas. The server defines procedures (queries, mutations, subscriptions) in a router, and the client infers all types from the exported AppRouter type.

When to use: TypeScript full-stack apps needing type-safe API layers, monorepos sharing types, real-time subscriptions, rapid API iteration without OpenAPI/GraphQL overhead.

When NOT to use: Public APIs consumed by non-TypeScript clients (use REST/GraphQL), polyglot backends, projects requiring OpenAPI spec generation as primary output.

Quick Reference

PatternAPIKey Points
InitializeinitTRPC.context<Ctx>().create()Single entry point, configure once
Routert.router({ ... })Nest routers with t.mergeRouters()
Queryt.procedure.input(schema).query(fn)Read operations, cached by clients
Mutationt.procedure.input(schema).mutation(fn)Write operations
Subscriptiont.procedure.subscription(fn)Real-time via WebSocket or SSE
Middlewaret.middleware(fn)Chain with .use(), extend context via next({ ctx })
Standalone middlewareexperimental_standaloneMiddleware<{}>()Reusable with explicit type constraints
ContextcreateContext({ req, res })Per-request, passed to all procedures
Server callert.createCallerFactory(router)Type-safe server-side procedure calls
Errorthrow new TRPCError({ code, message })Mapped to HTTP status codes
Error formatterinitTRPC.create({ errorFormatter })Customize error shape, expose Zod errors
Input validation.input(zodSchema)Multiple .input() calls merge (intersection)
Output validation.output(zodSchema)Strip extra fields from responses
React hookstrpc.useQuery() / trpc.useMutation()Built on @tanstack/react-query
React utilstrpc.useUtils()Invalidate, prefetch, setData on cache
Suspense querytrpc.useSuspenseQuery()Suspense-compatible data fetching
React subscriptiontrpc.useSubscription(input, opts)onData callback for real-time events
Vanilla clientcreateTRPCClient<AppRouter>({ links })No React dependency
Batch linkhttpBatchLink({ url })Batches requests in single HTTP call
Stream linkhttpBatchStreamLink({ url })Streams responses as they resolve
WS linkwsLink({ client: wsClient })WebSocket transport for subscriptions
Split linksplitLink({ condition, true, false })Route operations to different transports
Logger linkloggerLink()Debug request/response in development
Data transformerinitTRPC.create({ transformer })Serialize Dates, Maps, Sets (superjson)
Fetch adapterfetchRequestHandler({ endpoint, req })Cloudflare Workers, Deno, Bun, Next.js
Procedure chainingpublicProcedure.use(auth).use(rateLimit)Build reusable procedure bases

Common Mistakes

MistakeCorrect Pattern
Exporting the full t objectExport only t.router, t.procedure, t.middleware, t.createCallerFactory
Creating context inside procedureCreate context in adapter setup, flows through automatically
Using any for context typeDefine context type with initTRPC.context<MyContext>().create()
Catching errors in proceduresLet errors propagate; use onError in adapter or error formatter
Importing server code on clientImport only type AppRouter, never runtime server code
Using createCaller in production request handlersUse createCallerFactory for type-safe reusable callers
Defining input without validationAlways validate with Zod, Valibot, or ArkType schemas
Nesting routers incorrectlyUse dot notation in keys or t.mergeRouters(), not deep nesting
Different transformers on client/serverBoth sides must use the same transformer (e.g., superjson)
Creating QueryClient inside component renderCreate once outside component or use useState initializer
Manual TypeScript generics on hooksType the router procedures; let inference propagate to client
Not passing signal to fetch in queryFntRPC React handles abort signals automatically

Installation

pnpm add @trpc/server @trpc/client @trpc/react-query @tanstack/react-query zod

For subscriptions, add ws (server) and configure wsLink (client). For SSE-based subscriptions, use httpBatchStreamLink instead.

Delegation

  • Procedure discovery: Use Explore agent
  • Router architecture review: Use Task agent
  • Code review: Delegate to code-reviewer agent

If the tanstack-query skill is available, delegate query/mutation caching, invalidation, and optimistic update patterns to it. If the zod-validation skill is available, delegate input schema design and validation patterns to it. If the drizzle-orm skill is available, delegate database query patterns within procedures to it. If the vitest-testing skill is available, delegate test runner configuration and assertion patterns to it. If the hono skill is available, delegate Hono framework routing and middleware patterns to it.

References

发现
标签

此技能尚未发布标签。

版本
最新版本元数据

版本

v2026.09.24

发布时间

Sep 24, 2026

分类

未分类

许可证

未指定

源路径

skills/trpc

默认分支

main

最新提交

85e3a39

Tree SHA

a4c9e7b