All Resources
Framework
TypeScriptBackendAPI
May 24, 2024

tRPC Full-Stack Type Safety

Build end-to-end type-safe APIs with tRPC - no code generation needed.

Overview

tRPC enables you to build fully type-safe APIs without code generation. Your client has full type inference of your server, including errors and input validation.

Key Benefits

  • Zero-Config Type Safety: Automatic type inference client-to-server
  • Validation: Built-in Zod integration for runtime validation
  • Error Handling: Type-safe error responses
  • RPC Calls: Simple async function calls instead of REST endpoints
  • Middleware: Request/response interceptors

Quick Start

npm install @trpc/server @trpc/client zod

Server Setup

// server.ts
import * as trpc from '@trpc/server'
import { z } from 'zod'

const router = trpc.router()
  .query('hello', {
    input: z.object({ name: z.string() }),
    resolve({ input }) {
      return `Hello ${input.name}`
    }
  })
  .mutation('createUser', {
    input: z.object({ email: z.string().email() }),
    async resolve({ input }) {
      // Create user in database
      return { success: true }
    }
  })

export type AppRouter = typeof router

Client Usage

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

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

// Fully typed!
const result = await trpc.hello.query({ name: 'Alice' })

tRPC eliminates entire categories of bugs caused by API mismatches.

Curated by

Shyam