trpc

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.

Safety Notice

This listing is imported from skills.sh public index metadata. Review upstream SKILL.md and repository scripts before running.

Copy this and send it to your AI assistant to learn

Install skill "trpc" with this command: npx skills add oakoss/agent-skills/oakoss-agent-skills-trpc

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

Source Transparency

This detail page is rendered from real SKILL.md content. Trust labels are metadata-based hints, not a safety guarantee.

Related Skills

Related by shared tags or category signals.

Automation

playwright

No summary provided by upstream source.

Repository SourceNeeds Review
Automation

ui-ux-polish

No summary provided by upstream source.

Repository SourceNeeds Review
Automation

tanstack-form

No summary provided by upstream source.

Repository SourceNeeds Review
Automation

find-skills

No summary provided by upstream source.

Repository SourceNeeds Review