← All writing

Engineering· October 18, 2024 · 7 min

Type-Safe APIs Without Code Generation

How to achieve end-to-end type safety between your React frontend and Node.js backend using tRPC, Zod, and the power of TypeScript inference.

The Problem With REST and Types

With a traditional REST API, your types live in two places: the backend response shape and the frontend type definition. They drift apart. You add a field on the backend, forget to update the frontend type, and TypeScript happily lets you ship broken code.

Code generation (OpenAPI → TypeScript) helps but adds friction: you need to run a generator, commit the output, and keep it in sync.

tRPC: Types Through the Network

tRPC shares your router types directly between server and client — no code generation, no HTTP contracts to maintain.

// server/router.ts
const appRouter = router({
  getUser: publicProcedure
    .input(z.object({ id: z.string() }))
    .query(async ({ input }) => {
      return db.user.findUnique({ where: { id: input.id } })
    }),
})

export type AppRouter = typeof appRouter
// client/component.tsx
const { data } = trpc.getUser.useQuery({ id: '123' })
// data is fully typed — no manual type definitions needed

If you rename a field on the server, TypeScript immediately errors on every client call site.

Zod for Runtime Validation

Zod schemas do double duty: they validate input at runtime AND produce TypeScript types.

const UserSchema = z.object({
  id: z.string(),
  email: z.string().email(),
  age: z.number().min(0).max(150),
})

type User = z.infer<typeof UserSchema>

One schema, two purposes: runtime safety and compile-time types.

When to Use tRPC

tRPC is ideal when your frontend and backend share a repository. If you are building a public API consumed by third parties, REST with OpenAPI is the right choice.