End-to-end typesafe API framework for full-stack TypeScript applications without code generation or schemas.
- Language
- TypeScript
- License
- MIT
- Running for
- 4 years
- Team
- 1M+ MAU
Why this architecture
tRPC connects backend procedure implementations directly to frontend React hooks with zero-boilerplate type inference.
Tech stack by layer
6 technologies · audited Sep 17, 2026- ReactClient-side hooks for reactive querying, mutations, and server component hydration
- Next.jsFull-stack framework integration supporting Pages router, App router, and server actions
- TanStack QueryAsynchronous state caching, automatic refetching, and query invalidation engine
- TypeScriptCore type inference engine propagating router schemas to client callers without code generation
- Node.jsServer runtime executing RPC procedure handlers and standard HTTP/WS adapters
- TurborepoMonorepo build orchestrator caching cross-package compilation and test tasks
tRPC architecture diagram
Open SVGDiagram as text
- React / Next.js client (hooks · server components) → TanStack Query v5 (cache · refetch · invalidate): query options
- TanStack Query v5 (cache · refetch · invalidate) → Link chain (httpBatch · split · ws links): fetch
- Vanilla client (typed proxy caller) → Link chain (httpBatch · split · ws links): call
- Link chain (httpBatch · split · ws links) → Server adapters (Fetch · Next · Express · Lambda): HTTP / WS
- Server adapters (Fetch · Next · Express · Lambda) → tRPC router (typed procedures): resolve
- tRPC router (typed procedures) → AppRouter type (inferred, no codegen): export type
Key architectural decisions
4 decisions- 01
Zero-Codegen Type Inference via TypeScript Generics
Exports router type signatures directly across monorepos so client SDKs receive autocompletion and compiler validation without build-time code generation.
- 02
Modular Link Architecture for Request Pipelines
Implements composable links (httpBatchLink, splitLink, wsLink) that support request batching, retries, and data streaming.
- 03
First-Class TanStack Query Wrapper
Wraps TanStack Query v5 to provide type-safe query options, mutation hooks, and infinite scroll utilities matching router procedure definitions.
- 04
Universal Server Adapters
Provides standalone adapters for standard Fetch API, Next.js App Router, Express, Fastify, AWS Lambda, and WebSockets.
How tRPC is built
How tRPC is structured
The tRPC codebase is organized as a pnpm monorepo managed with Turborepo:
packages/server: The foundational server package where routers, procedures, middleware chains, context resolvers, and output transformers are defined. It contains standalone runtime adapters inadapters/for Express, Fastify, Fetch API, AWS Lambda, and WebSockets.packages/client: The client-side RPC proxy runtime. It defines the Link architecture (httpBatchLink,httpLink,wsLink,splitLink,loggerLink) that controls batching and network transport.packages/react-query&packages/tanstack-react-query: The integration layer wrapping TanStack Query v5 to deliver reactive query hooks, mutations, and query client utilities.packages/next: Specialized adapters and higher-order functions for Next.js (supporting Pages router SSR and Next.js App Router Server Components).packages/openapi: Optional utility for generating OpenAPI documentation specs from tRPC router definitions.packages/upgrade: Automated CLI migration codemods (jscodeshift) assisting developers across major version upgrades.
Frontend
On the frontend, tRPC provides a proxy-based client interface integrated with React and TanStack Query:
- Proxy Callers: Developers interact with
trpc.<procedure>.useQuery()ortrpc.<procedure>.useMutation(). Procedure paths map directly to server router trees with full autocompletion and hover documentation. - RSC Support: Includes dedicated utilities for React Server Components (
@trpc/next/app-dir) allowing direct server-side data fetching without HTTP round-trips. - Data Serialization: Built-in compatibility with transformers like Superjson and Devalue preserves JavaScript types across the wire (such as
Date,Map,Set, andBigInt).
Backend & APIs
The backend router is constructed programmatically in TypeScript:
- Procedure Builders: Procedures are defined as queries, mutations, or subscriptions, validated using input schemas (Zod, Valibot, ArkType, or Yup).
- Middleware Chains: Middleware functions allow cascading authentication, input sanitization, timing, and error handling through procedural pipelines.
- Adapters: The core router is completely runtime-agnostic. Pre-built adapters transform HTTP request/response objects into tRPC caller invocations.
Data & persistence
tRPC does not mandate or bundle a specific database engine. In full-stack applications, developers query ORMs (Prisma, Drizzle, Kysely) or key-value stores directly inside procedure resolver functions. The server context passes database connection pools and authenticated session objects into each procedure invocation.
Realtime / collaboration
tRPC supports realtime event streams using WebSockets and Server-Sent Events:
- WebSocket Link: The
wsLinkadapter establishes persistent duplex communication for subscription procedures. - Observables: Realtime subscriptions emit AsyncIterables or RxJS-style observables that stream server data directly into frontend UI listeners.
Build, test & deploy
The build pipeline relies on tsdown and Turborepo:
- Packages are compiled to dual CommonJS and ESM distributions with TypeScript declaration files (
.d.ts). - Tests are executed with Vitest across node environments and edge runtimes (
examples/cloudflare-workers,examples/vercel-edge-runtime). - GitHub Actions workflows automate semantic release publishing, dependency updates, and typechecking matrices.
Self-hosting notes
tRPC is an application-level library embedded directly inside host applications:
- Install
@trpc/server,@trpc/client, and matching adapter packages into full-stack frameworks or standalone microservices. - No external standalone servers, daemon processes, or proxy gateways need to be provisioned.
What to copy (and what not to)
What to copy:
- Zero-codegen type sharing via TypeScript's
typeof AppRouterexport pattern, dramatically improving developer velocity. - The link pipeline pattern on the client, which allows customizing batching, header injection, retry strategies, and logging.
- Input schema polymorphism supporting multiple validation libraries (Zod, Valibot, ArkType) through standard schema contracts.
What not to copy:
- Exposing complex internal type utility maps across multiple separate packages; modern library designs benefit from bundling core type helpers into unified modules to minimize TypeScript compiler memory overhead.
Sources & repo audit
- package.json (Monorepo root scripts and package definitions)
- packages/server/package.json (Core tRPC server library and adapters)
- packages/client/package.json (tRPC client library and request links)
- packages/tanstack-react-query/package.json (TanStack React Query integration package)
Independent analysis of repository at github.com/trpc/trpc. Spotted an inaccuracy? Use the claim form to request a correction.
Show this stack on your README or website
[](https://stackitfast.com/project/trpc)Paste it into your README. It shows your current stack and links to this page.
Scaffold it with your agent
Paste this prompt into Claude Code, Cursor, Windsurf or AGY to start a project with tRPC's architecture.
- 1Copy the promptThe full markdown spec, with every layer and decision.
- 2Open your AI toolClaude Code, Cursor, Windsurf or Copilot, in a new repo.
- 3Paste and scaffoldUse it as the first instruction; review before you ship.
# MISSION: Scaffold "tRPC" Production Architecture
You are an expert Senior Staff Software Architect and Full-Stack Engineer. Your mission is to scaffold and implement a production-grade, highly reliable, and modular codebase following the proven architecture of **tRPC**.
---
## 1. PROJECT SPECIFICATIONS & BENCHMARK
- **Reference Architecture**: tRPC
- **What It Does**: End-to-end typesafe API framework for full-stack TypeScript applications without code generation or schemas.
- **Domain & Category**: End-to-End Typesafe API Framework
- **Production Scale**: 1M+ MAU
- **Development Mode**: HYBRID
- **Architectural Rationale**: tRPC connects backend procedure implementations directly to frontend React hooks with zero-boilerplate type inference.
- **Live Website Reference**: https://trpc.io
- **Source Repository**: https://github.com/trpc/trpc
---
## 2. PRODUCTION TECH STACK
- **Full Stack Array**: TypeScript, React, Next.js, TanStack Query, Turborepo, Node.js
- **Primary Language(s)**: TypeScript, MDX, JavaScript, CSS
- **License of the reference repo**: MIT
- **Frontend**: React — Client-side hooks for reactive querying, mutations, and server component hydration; Next.js — Full-stack framework integration supporting Pages router, App router, and server actions; TanStack Query — Asynchronous state caching, automatic refetching, and query invalidation engine
- **Backend & APIs**: TypeScript — Core type inference engine propagating router schemas to client callers without code generation; Node.js — Server runtime executing RPC procedure handlers and standard HTTP/WS adapters
- **Infrastructure & deploy**: Turborepo — Monorepo build orchestrator caching cross-package compilation and test tasks
---
## 3. KEY ARCHITECTURAL DECISIONS (audited from https://github.com/trpc/trpc @ 8b649ad)
1. **Zero-Codegen Type Inference via TypeScript Generics**: Exports router type signatures directly across monorepos so client SDKs receive autocompletion and compiler validation without build-time code generation.
2. **Modular Link Architecture for Request Pipelines**: Implements composable links (httpBatchLink, splitLink, wsLink) that support request batching, retries, and data streaming.
3. **First-Class TanStack Query Wrapper**: Wraps TanStack Query v5 to provide type-safe query options, mutation hooks, and infinite scroll utilities matching router procedure definitions.
4. **Universal Server Adapters**: Provides standalone adapters for standard Fetch API, Next.js App Router, Express, Fastify, AWS Lambda, and WebSockets.
---
## 4. NON-NEGOTIABLE ARCHITECTURAL GUARDRAILS
1. **Monorepo & Modular Separation**:
- Structure as a Turborepo monorepo with strict package boundaries:
- `apps/web`: Application UI, routing, layouts, and server endpoints.
- `packages/ui`: Shared design tokens, CSS variables, and Radix UI primitive components.
- `packages/db`: Database schemas, client singleton, declarative migrations, and seed scripts.
- `packages/config`: Shared TypeScript, ESLint, and build configurations.
2. **Strict Type Safety & Zero `any` Policy**:
- Enable `strict: true`, `noImplicitAny: true`, and `strictNullChecks: true`.
- Validate ALL external inputs, API request bodies, and query parameters with **Zod** schemas before execution.
3. **Frontend & Rendering Guidelines**:
- Utilize Next.js 15 App Router: default to React Server Components (RSC) for data fetching. Handle mutations through Server Actions with Zod validation. Keep 'use client' directives restricted strictly to interactive leaf components.
4. **Design System & Aesthetics**:
- Keep every color, radius, shadow and font in a single token file (CSS variables) and consume tokens everywhere; never hardcode hex values in components.
- Prefer crisp 1px borders and one subtle shadow scale over blurry default shadows. Pair one sans-serif for body/headings with one monospace for tags, badges, metrics, and code.
5. **Data Layer & Reliability**:
- Write declarative schema definitions with foreign keys, composite indexes on queried filters, and automated timestamp triggers.
- Use connection pooling and prepared statements for serverless database execution.
---
## 5. STEP-BY-STEP SCAFFOLDING ROADMAP
- **Phase 1: Workspace & Root Config**: Initialize package manager, monorepo configuration (`turbo.json`, `tsconfig.base.json`, `package.json`).
- **Phase 2: Database Schema & Client**: Set up the data layer: client, connection pool, models, and migration scripts.
- **Phase 3: Design Tokens & UI Primitives**: Build accessible `Button`, `Input`, `Card`, `Badge`, and layout wrappers inside `packages/ui`.
- **Phase 4: Core Application Routes & Handlers**: Implement primary authentication, user session handling, and application routes.
- **Phase 5: Quality Assurance & Build Verification**: Run `tsc --noEmit`, ESLint, Prettier, and smoke test suites to ensure zero compilation or runtime errors.
---
## 6. EXECUTION INSTRUCTIONS
1. Review all specifications, architectural guardrails, and stack choices above.
2. Present the full monorepo directory tree structure.
3. Systematically generate the complete, production-ready codebase according to the 5-phase roadmap above — starting with the root workspace setup, followed by the database schema, UI design system package, and full-stack application routes until the repository is fully scaffolded and ready to run.Frequently asked about tRPC
Does tRPC require running a build-step code generator to produce client types?
No, tRPC leverages TypeScript type inference directly; importing the AppRouter type into the client yields instant autocompletion and compile-time checks.
Can tRPC be used with backend runtimes other than Next.js?
Yes, tRPC provides first-class server adapters for Express, Fastify, AWS Lambda, Cloudflare Workers, and standard Web Fetch handlers.
One email a month: new deep dives and stack trends
New source-audited architectures, head-to-head comparisons and the monthly stack report. No spam, unsubscribe anytime.
Similar architectures
- RefineHybridEnterprise Internal Tool & CRUD Framework · 20+ PeopleShares React · TypeScript · TanStack Query
- shadcn/uiHybridCopy-Paste UI Component Architecture · 1M+ MAUShares React · TypeScript · Turborepo
- Supabase StudioClassicDeveloper Tool · 20+ peopleShares Next.js · React · TypeScript
- Fast Jev CompactionClassicClaude Code Plugin · SoloShares TypeScript · Node.js
- BrowserlessClassicHeadless Browser Automation Infrastructure · 2-5 PeopleShares TypeScript · Node.js
- TinycastHybridNative macOS Launcher & Clipboard Manager · Solo / 2-5 peopleShares React · Next.js