Back to Blog
Backend

Type-Safe APIs in Next.js with tRPC and Zod

Developer Hub
1/11/2026
1 min read min read

tRPC plus Zod gives you end-to-end type safety without OpenAPI boilerplate.

Why this stack works

  • Shared types: inputs/outputs stay in sync between client and server.
  • Runtime validation: Zod schemas protect your handlers from bad inputs.
  • No codegen step: faster iteration and fewer tooling dependencies.

Minimal setup outline

  • Add @trpc/server, @trpc/client, @trpc/react-query, and zod.
  • Create a router with procedures that validate input via Zod.
  • Expose a Next.js handler for /api/trpc and wrap your app with the tRPC provider.

Authoring tips

  • Co-locate Zod schemas with procedures; export inferred types for components.
  • Prefer input: z.object({ ... }) over unknown parsing to avoid surprises.
  • Return discriminated unions for errors you expect the client to handle.

Testing

  • Unit test procedures directly with in-memory context.
  • Add contract tests to ensure shape and defaults stay stable.
  • Log procedure name, duration, and validation failures for observability.

Next steps

  • Add middleware for auth/role checks at the router level.
  • Generate a public type bundle for shared UI packages if needed.
  • Combine with Next.js caching (revalidate/fetch cache) for high-traffic queries.