惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Jina AI
Jina AI
V
Visual Studio Blog
博客园 - 司徒正美
TaoSecurity Blog
TaoSecurity Blog
博客园 - 聂微东
IT之家
IT之家
博客园_首页
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
C
Cyber Attacks, Cyber Crime and Cyber Security
博客园 - Franky
雷峰网
雷峰网
罗磊的独立博客
S
Schneier on Security
C
Cybersecurity and Infrastructure Security Agency CISA
The Cloudflare Blog
T
Tailwind CSS Blog
B
Blog RSS Feed
H
Help Net Security
T
The Blog of Author Tim Ferriss
C
CXSECURITY Database RSS Feed - CXSecurity.com
T
Threatpost
C
CERT Recently Published Vulnerability Notes
博客园 - 三生石上(FineUI控件)
P
Palo Alto Networks Blog
I
Intezer
G
GRAHAM CLULEY
Engineering at Meta
Engineering at Meta
S
Securelist
J
Java Code Geeks
V
V2EX
Y
Y Combinator Blog
Simon Willison's Weblog
Simon Willison's Weblog
L
LINUX DO - 热门话题
云风的 BLOG
云风的 BLOG
Spread Privacy
Spread Privacy
MongoDB | Blog
MongoDB | Blog
P
Privacy International News Feed
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
B
Blog
Forbes - Security
Forbes - Security
Google Online Security Blog
Google Online Security Blog
Help Net Security
Help Net Security
S
SegmentFault 最新的问题
N
Netflix TechBlog - Medium
Webroot Blog
Webroot Blog
Microsoft Security Blog
Microsoft Security Blog
SecWiki News
SecWiki News
Scott Helme
Scott Helme
aimingoo的专栏
aimingoo的专栏
N
News and Events Feed by Topic

The Practical Developer

The Libuv Thread Pool Trap: Why Node.js Async APIs Stall Under Load Postgres Covering Indexes with INCLUDE: Eliminate Heap Fetches on Read-Heavy Workloads Postgres DISTINCT ON: The Fastest Way to Get the Latest Row Per Group Postgres Transaction Isolation: The Anomalies Your App Actually Faces in Production Linux TCP Tuning for Node.js Microservices: The Kernel Settings That Stop Silent Connection Drops Under Load Postgres HOT Updates and Fillfactor: Why Not All Writes Are Created Equal Database Connection Pool Leaks: Finding the Promise That Never Returns Its Seat Linux OOM Killer in Production: Why Your Node.js Containers Die Without a Stack Trace Postgres Materialized Views: Refresh Strategies That Do Not Lock Your Dashboards API Dependency Health Checks: Why /health Is Not Enough Authorization with Zanzibar Tuples: How Google Manages Permissions and How To Build the Same Check in Node.js Postgres Advisory Locks: The 20-Character Primitive That Replaces Redis for Coordination Dead Letter Queues: The Message Queue Pattern That Saves You at 2 a.m. File Descriptor Exhaustion: The Kernel Limit That Silently Drops Node.js Connections Graceful Degradation: The Pattern That Turns Total Outages into Partial Success PostgreSQL Full-Text Search: Dropping Elasticsearch for 90% of Use Cases S3 Presigned Multipart Uploads: Stop Your API Server from Being a File Upload Bottleneck MessagePack vs JSON: The Binary Serialization Switch That Cut Our Internal RPC Overhead by 40% DNS Caching in Node.js: The Silent Cause of Production Latency Spikes Reliable Cron Jobs: The Pattern That Stops Double Runs, Missed Executions, And The 2 AM Page GraphQL Query Complexity: Stop the OOM Query Before It Reaches Your Resolver Node.js Event Loop Lag: The Hidden Metric Behind Random Latency Spikes API Request Validation with Zod: The Schema That Catches Bad Input Before It Corrupts Your Database Load Shedding in Node.js: How to Reject Traffic Before You Drown Request Hedging: Cut Tail Latency In Half Without Overprovisioning Git Bisect: The Automated Binary Search That Finds Breaking Commits in Minutes Node.js Garbage Collection Tuning: Stop Letting V8 Pause Your Event Loop Node.js Server Timeouts: The Settings That Stop Slow Clients from Holding Sockets Hostage Postgres BRIN Indexes: The Time-Series Secret That Shrinks Indexes by 99% Event Sourcing with PostgreSQL: The Pragmatic 80% Solution Node.js Cluster Mode: Scaling the Event Loop Across CPU Cores Postgres Partial Indexes: Stopping Soft Deletes from Ruining Your Query Performance Request Coalescing with the Singleflight Pattern: Stop Drowning Your Database on Every Cache Miss The Bulkhead Pattern: Why One Slow Endpoint Should Not Drown Your Whole Service Node.js AsyncLocalStorage: End-to-End Request Context Without the Propagation Hell Postgres Deadlocks: Logging the Victim, Reproducing the Race, and Fixing the Lock Order Your Node.js HTTP Client Is the Bottleneck: Connection Pool Tuning That Works Optimistic Locking in Postgres: Stop Losing Data to Race Conditions Postgres Read Replicas: Stop Serving Stale Data to Your Users Cursor Pagination: Why Offset Queries Explode at Scale and How to Fix Them Node.js Worker Threads: 60 Lines That Stop a CSV Upload from Timing Out Every Other Request Reliable Webhook Delivery: Architecture for Outbound HTTP You Can Trust Request Timeouts and Deadline Propagation: Stop the Chain of Slowness Advanced Security Practices in Node.js Graceful Shutdown in Node.js: The 40 Lines That Stop 502s During Deploys Finding Node.js Memory Leaks with Heap Snapshots Idempotency Keys in 30 Lines: Stop Your Webhook From Charging Customers Twice Backpressure In Node.js: The Fix For Slow-Motion Queue Meltdowns Retries Done Right: Jitter, Budgets, and the Stampede You Did Not See Coming The Cache Stampede: Why Your "Just Add Redis" Layer Crashes Postgres at 3 a.m. Postgres SKIP LOCKED: An 80-Line Job Queue You Can Run Without Redis Stop Doing Work Nobody Wants: AbortController in Node.js, Done Right The N+1 Query Problem: We Found 23 In One Codebase And Killed Every One I Tried 5 AI Coding Tools for a Month. Here Is What I Actually Use CI/CD From Zero to Production in 30 Minutes With GitHub Actions Node.js vs Bun vs Deno: Which Runtime Should You Pick in 2025? Kubernetes Resource Requests And Limits: The Numbers That Decide If Your Cluster Is Stable The Three Pillars of Observability Are A Myth: What Actually Matters In Production pnpm Vs npm Vs yarn Vs Bun For Monorepos: Which One Earns The Migration In 2024 JSONB Indexing In Postgres: GIN Vs Expression Indexes, And When Each Is The Right Choice A Code Review Checklist That Ends The Same Three Arguments Every Sprint gRPC Vs REST In 2024: When The Switch Pays For Itself React Suspense For Data Fetching: The Pattern That Replaces Half Your Loading State Code The Five-Stage Rollout: How To Ship A Risky Change Without Holding Your Breath GitHub Actions In A Monorepo: Caching, Path Filters, And Secret Boundaries That Actually Work The Blameless Postmortem That Actually Improves Things: A Template And Six Hard-Won Rules Recursive CTEs In Postgres: How To Query A Tree Without N Round Trips Node.js Streams: When They Actually Help, And When They Just Add Complexity Playwright Vs Cypress In 2024: The Honest Comparison Of Which One Earns The Test Time React Server Components: The Mental Model That Makes The "use client" Boundary Obvious Pod Disruption Budgets: The K8s Object That Keeps Your Service Up During Cluster Maintenance Postgres LISTEN/NOTIFY: The Pub/Sub You Already Have And Are Not Using Chaos Engineering Starter Kit: The Five Drills That Don't Need Netflix-Scale Spec-Driven API Development With OpenAPI: How To Stop Drifting From Your Docs Kubernetes Autoscaling Beyond CPU: The Custom-Metric HPA Pattern That Actually Works Postgres Partitioning For Time-Series: The Boring Setup That Saves Your Database Distributed Locks With Redis: An Honest Look At Redlock And When You Don't Need It HTTP/2 vs HTTP/3: What Actually Changes For Your App, And What Doesn't Image Optimization For The Web In 2023: srcset, AVIF, And The Lighthouse Score You Actually Want Kafka vs RabbitMQ: A Decision Tree That Doesn't Hate You UUID vs Bigint Primary Keys In Postgres: The Index Math That Decides For You Flame Graphs: How To Find The Slow Function In 30 Seconds Without Profiling Theatre Postgres Streaming Vs. Logical Replication: Which One Solves Your Actual Problem ESLint Rules That Earn Their Keep: The Twelve I Enable On Every Project Pre-Commit Hooks That Pay For Themselves: Husky, lint-staged, And The Five Rules That Stick Zero-Downtime Database Migrations: The Six-Step Pattern That Rules Them All Circuit Breakers In Node.js: 50 Lines That Stop A Failing Dependency From Taking Down Your Service Postgres VACUUM Is Not Magic: How Your Hot Table Bloats To 80GB And How To Fix It Kubernetes Liveness And Readiness Probes: The Difference That Causes Half Your Outages Rate Limiting In Production: A Token Bucket In 30 Lines Of Redis The Outbox Pattern: How To Stop Losing Events When Postgres And Kafka Disagree Load Testing With k6: The Three Scenarios That Find Real Bugs (Not Synthetic Numbers) Postgres Row-Level Security For Multi-Tenant Apps: The Pattern That Stops You From Leaking Data Rebase vs. Merge: The Team Policy That Ends The Argument Forever OpenTelemetry in Node.js: Distributed Tracing That Actually Helps During an Incident Feature Flags That Pay Rent: The 4 Flag Types And When To Delete Each ETag, Last-Modified, and the Caching Headers Most APIs Get Wrong Connection Pooling Without the Cargo Cult: pgbouncer in 100 Lines of Config JSONB Is Not a Schema: When To Reach For It in Postgres, And When To Stop Bash Strict Mode: The Three Lines That Stop Your Deploy Script From Lying To You
tRPC in Production: Type-Safe APIs Without REST or GraphQL
The Practica · 2026-06-26 · via The Practical Developer

The bug report read: “User creation fails silently on the settings page.” You opened the network tab, found the POST /users call, and the response body said "email": ["expected a valid email address"]. The client code sent email_address (with an underscore). The server expected email (without one). The TypeScript types on the client said email_address: string. The server types said email: string. Both were hand-written. Both compiled. Nothing caught the mismatch except a user staring at an unhelpful error toast.

This kind of bug is the norm in REST and GraphQL codebases, not the exception. You define types on the server. You redefine them on the client. You pray they stay in sync. Sometimes you generate clients from OpenAPI or GraphQL introspection, which helps, but adds a build step, a spec file, and a code generator that can produce its own class of bugs.

tRPC takes a different approach. Instead of defining your API through a schema language and generating types from it, tRPC makes your TypeScript types the schema. The server exports its type. The client imports it. The compiler enforces alignment. If you rename a field on the server, the client build breaks. That is the goal: a compile-time error instead of a production bug.

This post covers a production-grade tRPC setup with authentication, structured error handling, middleware, request validation, and rate limiting. By the end, you will have a working server and client that share types without a build step, a spec file, or a code generator.

The mental model

tRPC is not a framework. It is a function call that happens over HTTP. Every procedure on the server is a plain TypeScript function. Every call from the client is a typed function invocation. The transport layer is HTTP POST under the hood, but you never touch req, res, or fetch directly.

The key insight is that tRPC uses TypeScript’s type inference to encode the API contract. The server defines a router object. The client creates a proxy from the router’s type. At runtime, the client calls a function, tRPC serializes the arguments as JSON over HTTP, the server deserializes them, runs the function, and sends the result back as JSON. On the client, the return type is the server’s TypeScript return type, inferred at compile time through the proxy.

No OpenAPI file. No code generator. No hand-written fetch wrappers. The compiler is your contract validator.

Bootstrapping the server

Start with the server. Install the core packages:

npm install @trpc/server @trpc/client zod

Define a simple router with one procedure:

// src/server/trpc.ts
import { initTRPC } from '@trpc/server';
import { z } from 'zod';

const t = initTRPC.create();

export const router = t.router;
export const publicProcedure = t.procedure;
// src/server/index.ts
import { z } from 'zod';
import { router, publicProcedure } from './trpc';

const appRouter = router({
  greet: publicProcedure
    .input(z.object({ name: z.string().min(1) }))
    .query(({ input }) => {
      return { message: `Hello, ${input.name}!` };
    }),
  createUser: publicProcedure
    .input(z.object({
      email: z.string().email(),
      name: z.string().min(1),
    }))
    .mutation(async ({ input }) => {
      // In real code, insert into the database
      const user = { id: crypto.randomUUID(), ...input };
      return user;
    }),
});

export type AppRouter = typeof appRouter;

The router distinguishes between queries (GET-like, idempotent) and mutations (POST-like, state-changing). Both accept Zod schemas for input validation. If the client sends an invalid name, Zod throws before the handler runs, and tRPC returns a structured validation error.

Now wire up the HTTP server. The recommended adapter for Node.js is Fastify, but Express works too:

// src/server/http.ts
import { createHTTPServer } from '@trpc/server/adapters/standalone';
import { appRouter } from './index';

const server = createHTTPServer({
  router: appRouter,
  createContext() {
    return {}; // We will fill this in with auth
  },
});

server.listen(3000);
console.log('Server running on http://localhost:3000');

That is the entire server. Sixteen lines of application code, and you have a typed API endpoint. No routing config, no middleware stack for JSON parsing, no manual error handling for invalid input.

The client

On the client side, install the client package:

npm install @trpc/client

Import the type from the server:

// src/client.ts
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
import type { AppRouter } from '../server/index';

const client = createTRPCProxyClient<AppRouter>({
  links: [httpBatchLink({ url: 'http://localhost:3000' })],
});

// Fully typed, no code generation needed
const result = await client.greet.query({ name: 'Alice' });
console.log(result.message); // "Hello, Alice!"

const user = await client.createUser.mutate({
  email: 'alice@example.com',
  name: 'Alice',
});
console.log(user.id);

If you rename name to firstName in the server’s Zod schema, the client file will not compile until you update the call site. That is the entire value proposition. No runtime surprises.

The httpBatchLink automatically batches multiple requests made within a short time window into a single HTTP call. This is significant for performance: rendering a dashboard that calls five procedures does not result in five round trips. tRPC coalesces them into one HTTP request with an array of inputs and returns an array of outputs. The client API remains async function calls. The batching is transparent.

Authentication with context

Public procedures are rare in production. Most endpoints need to know who is calling them. tRPC handles this through context, a per-request object you populate in the adapter’s createContext function and access in every procedure.

First, add a context creator that extracts and verifies a token:

// src/server/context.ts
import { inferAsyncReturnType } from '@trpc/server';
import { CreateFastifyContextOptions } from '@trpc/server/adapters/fastify';

export async function createContext({ req, res }: CreateFastifyContextOptions) {
  // Extract the Authorization header
  const header = req.headers.authorization;
  const token = header?.startsWith('Bearer ') ? header.slice(7) : null;

  // Verify the token. This is a placeholder; use JWT or your auth provider.
  let user: { id: string; role: string } | null = null;
  if (token) {
    // verifyJwt(token) returns decoded payload or throws
    user = { id: 'user_123', role: 'admin' };
  }

  return { user, req, res };
}

export type Context = inferAsyncReturnType<typeof createContext>;

Then update the tRPC initialization to use the context type:

// src/server/trpc.ts
import { initTRPC } from '@trpc/server';
import type { Context } from './context';

const t = initTRPC.context<Context>().create();

export const router = t.router;
export const publicProcedure = t.procedure;

Now create an authenticated procedure that rejects unauthenticated requests:

// src/server/trpc.ts (continued)
import { TRPCError } from '@trpc/server';

const isAuthenticated = t.middleware(({ ctx, next }) => {
  if (!ctx.user) {
    throw new TRPCError({
      code: 'UNAUTHORIZED',
      message: 'You must be logged in to access this resource',
    });
  }
  return next({
    ctx: { user: ctx.user },
  });
});

export const protectedProcedure = t.procedure.use(isAuthenticated);

Use protectedProcedure anywhere you need authentication:

// src/server/index.ts
const appRouter = router({
  getProfile: protectedProcedure
    .query(({ ctx }) => {
      return { id: ctx.user.id, role: ctx.user.role };
    }),
  deleteUser: protectedProcedure
    .input(z.object({ userId: z.string() }))
    .mutation(async ({ ctx, input }) => {
      if (ctx.user.role !== 'admin') {
        throw new TRPCError({
          code: 'FORBIDDEN',
          message: 'Only admins can delete users',
        });
      }
      // Delete the user from the database
    }),
});

The middleware pattern composes cleanly. Add a logging middleware, a rate-limiting middleware, or a tenant-isolation middleware with the same t.middleware() API. Each middleware can augment the context for downstream procedures.

Structured error handling

The TRPCError class maps to standard HTTP status codes:

CodeHTTP StatusWhen to use
PARSE_ERROR400Malformed request body
BAD_REQUEST400Validation failure (Zod handles this automatically)
UNAUTHORIZED401Missing or invalid authentication
FORBIDDEN403Authenticated but not allowed
NOT_FOUND404Resource does not exist
TIMEOUT408Procedure took too long
CONFLICT409Duplicate resource, version conflict
PRECONDITION_FAILED412Business rule violation
PAYLOAD_TOO_LARGE413Input exceeds limit
METHOD_NOT_SUPPORTED405Wrong procedure type
TOO_MANY_REQUESTS429Rate limited
CLIENT_CLOSED_REQUEST499Client disconnected
INTERNAL_SERVER_ERROR500Unexpected error

On the client, you catch these with standard try/catch:

import { TRPCClientError } from '@trpc/client';

try {
  await client.deleteUser.mutate({ userId: 'user_456' });
} catch (error) {
  if (error instanceof TRPCClientError) {
    console.error(error.message); // "Only admins can delete users"
    console.error(error.data.code); // "FORBIDDEN"
    console.error(error.data.httpStatus); // 403
  }
}

No parsing the response body. No checking error.response.status. The type system already knows what the error looks like.

Request validation beyond basic types

Zod schemas inline in procedure definitions work well for simple cases. For complex mutations, extract the schema into a separate file and reuse it in tests:

// src/schemas/user.ts
import { z } from 'zod';

export const createUserSchema = z.object({
  email: z.string().email('Must be a valid email address'),
  name: z.string().min(1, 'Name is required').max(100),
  role: z.enum(['user', 'admin', 'moderator']).default('user'),
  metadata: z.record(z.string()).optional(),
});

export type CreateUserInput = z.infer<typeof createUserSchema>;
// src/server/index.ts
import { createUserSchema } from '../schemas/user';

const appRouter = router({
  createUser: protectedProcedure
    .input(createUserSchema)
    .mutation(async ({ ctx, input }) => {
      // input is fully typed as CreateUserInput
    }),
});

Zod handles coercion, defaults, and refinements. Need to validate that a date range starts before it ends? Add a .refine():

const dateRangeSchema = z.object({
  start: z.coerce.date(),
  end: z.coerce.date(),
}).refine(data => data.start < data.end, {
  message: 'Start date must be before end date',
  path: ['start'],
});

All of these errors surface through tRPC’s standard error format. The client does not need special parsing logic for business rule violations.

Rate limiting with middleware

Add rate limiting as a reusable middleware:

// src/server/rateLimit.ts
import { TRPCError } from '@trpc/server';
import { t } from './trpc';

// Simple in-memory rate limiter; use Redis in production
const rateMap = new Map<string, { count: number; resetAt: number }>();

export const rateLimit = t.middleware(({ ctx, next, path }) => {
  const key = ctx.user?.id ?? ctx.req.ip;
  const now = Date.now();
  const windowMs = 60_000; // 1 minute
  const maxRequests = 100;

  const entry = rateMap.get(key);
  if (!entry || entry.resetAt < now) {
    rateMap.set(key, { count: 1, resetAt: now + windowMs });
    return next();
  }

  if (entry.count >= maxRequests) {
    throw new TRPCError({
      code: 'TOO_MANY_REQUESTS',
      message: 'Rate limit exceeded. Try again in 60 seconds.',
    });
  }

  entry.count++;
  return next();
});

export const rateLimitedProcedure = t.procedure.use(isAuthenticated).use(rateLimit);

Use rateLimitedProcedure for expensive endpoints like user creation or file upload.

Request batching and cache headers

tRPC’s httpBatchLink sends multiple queries in a single HTTP POST. This is great for performance but interacts poorly with HTTP caching proxies (CDNs, browser cache). Since batched requests use POST, they bypass most HTTP caches by default.

For read-heavy workloads where caching matters, use a separate httpLink (no batching) for queries that should be cacheable, and httpBatchLink for everything else. Configure the server to emit Cache-Control headers on individual queries:

// This requires a custom response in the context
// or using Fastify's reply object directly

Or use httpBatchLink for mutations and splitLink to route queries differently:

import { createTRPCProxyClient, httpBatchLink, httpLink, splitLink } from '@trpc/client';

const client = createTRPCProxyClient<AppRouter>({
  links: [
    splitLink({
      condition: (op) => op.type === 'query',
      true: httpLink({ url: 'http://localhost:3000' }),
      false: httpBatchLink({ url: 'http://localhost:3000' }),
    }),
  ],
});

This sends queries as individual GET requests (cacheable) and mutations as batched POSTs. You get the caching benefit for reads and the batching benefit for writes.

Error handling on the client

Every React project using tRPC should have an error boundary or a hook wrapper that surfaces server errors to users. tRPC provides @trpc/react-query for React integration, which wraps React Query under the hood. Here is a minimal React setup:

import { createTRPCReact } from '@trpc/react-query';
import type { AppRouter } from '../server/index';

export const trpc = createTRPCReact<AppRouter>();

function MyComponent() {
  const greeting = trpc.greet.useQuery({ name: 'Alice' });
  const createUser = trpc.createUser.useMutation();

  if (greeting.error) {
    return <div>Error: {greeting.error.message}</div>;
  }

  return (
    <div>
      <p>{greeting.data?.message}</p>
      <button onClick={() => createUser.mutate({ email: 'a@b.com', name: 'Alice' })}>
        Create
      </button>
    </div>
  );
}

React Query handles caching, retries, and stale data automatically. The useMutation hook exposes isLoading, error, and data states. You never serialize or deserialize a request manually.

The real trade-offs

tRPC is not universally better than REST or GraphQL. Here is what you give up:

No HTTP caching on most endpoints. tRPC uses POST by default. If your API serves millions of requests for the same data each day (a public read-only API), REST with GET and Cache-Control headers will outperform tRPC at the CDN level. The splitLink workaround above helps but adds complexity.

No public API documentation. There is no tRPC equivalent of Swagger UI. Third-party developers cannot open a browser and explore your API. tRPC is designed for first-party clients (your frontend, your mobile app, your internal services). If your API is public, stick with OpenAPI.

Tight coupling between server and client. This is the feature, not a bug, but it means the server and client must be in the same monorepo or share a package. Separate teams with separate deploy cadences will find the tight coupling painful.

WebSocket streaming is possible but not native. tRPC supports subscriptions via @trpc/server subscriptions, but the implementation is less mature than GraphQL subscriptions or raw WebSocket handlers.

Use tRPC when you control both ends of the API and want maximum type safety with minimum boilerplate. Use REST or GraphQL when you need caching, public documentation, or decoupled teams.

The production checklist

Before deploying tRPC to production, verify these points:

  • Middleware order: authentication before authorization before rate limiting.
  • Context is populated from the correct adapter (Fastify, Express, Next.js).
  • Error messages do not leak internal details in production (use t.procedure with custom error formatting).
  • batching is configured with maxBatchSize to prevent 50 KB request bodies.
  • The server adapter is behind your existing HTTPS and TLS termination.
  • Zod schemas are tested independently, not just through e2e tests.
  • File uploads use a separate endpoint or FormData, not tRPC (tRPC expects JSON).

The 60-line production server

Here is everything above combined into a server you can deploy:

import { initTRPC, TRPCError } from '@trpc/server';
import { createHTTPServer } from '@trpc/server/adapters/standalone';
import { z } from 'zod';

// --- Context ---
async function createContext({ req }: { req: Request }) {
  const token = req.headers.get('authorization')?.slice(7);
  const user = token ? { id: 'user_123', role: 'admin' } : null;
  return { user, req };
}
type Context = { user: { id: string; role: string } | null; req: Request };

// --- tRPC instance ---
const t = initTRPC.context<Context>().create();

// --- Middleware ---
const authMiddleware = t.middleware(({ ctx, next }) => {
  if (!ctx.user) throw new TRPCError({ code: 'UNAUTHORIZED' });
  return next({ ctx: { user: ctx.user } });
});

// --- Schemas ---
const userSchema = z.object({
  email: z.string().email(),
  name: z.string().min(1).max(100),
});

// --- Router ---
const appRouter = t.router({
  hello: t.procedure
    .input(z.object({ name: z.string() }))
    .query(({ input }) => `Hello, ${input.name}`),
  me: t.procedure.use(authMiddleware)
    .query(({ ctx }) => ({ id: ctx.user.id, role: ctx.user.role })),
  createUser: t.procedure.use(authMiddleware)
    .input(userSchema)
    .mutation(async ({ input }) => {
      // Insert into database
      return { id: crypto.randomUUID(), ...input };
    }),
});

export type AppRouter = typeof appRouter;

// --- HTTP ---
const server = createHTTPServer({
  router: appRouter,
  createContext,
});
server.listen(3000);

And the client:

import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
import type { AppRouter } from './server';

const client = createTRPCProxyClient<AppRouter>({
  links: [httpBatchLink({ url: 'http://localhost:3000' })],
});

const greeting = await client.hello.query({ name: 'Alice' });
const user = await client.createUser.mutate({
  email: 'alice@example.com',
  name: 'Alice',
});

Two files. Zero hand-written fetch calls. Zero type files to keep in sync. If this code compiles, the server and client agree on every field name, every type, and every optionality constraint. That is the entire point.

A note from Yojji

Building an API layer that eliminates entire categories of bugs at compile time is exactly the kind of engineering investment that pays for itself within the first few sprints. Yojji’s teams apply this same discipline to the full-stack applications they build, from TypeScript monorepos to cloud-native deployments, ensuring that type safety and production reliability are designed in from the start rather than bolted on after the fact.

Yojji is an international custom software development company founded in 2016, with offices in Europe, the US, and the UK. Their senior engineering teams specialize in the JavaScript ecosystem (React, Node.js, TypeScript), cloud platforms (AWS, Azure, GCP), and full-cycle product engineering, including the API architecture and validation patterns that keep production systems stable.