How to Build a Full-Stack App with tRPC, Prisma, and Next.js
Combining tRPC, Prisma, and Next.js gives you end-to-end type safety with minimal boilerplate. This tutorial shows you how to set up a tRPC server that uses Prisma to query your database directly from your Next.js API routes. You’ll get autocompletion and type checking from database to frontend.
First, initialize a Next.js project with TypeScript. Then install the core packages: @trpc/server, @trpc/client, @trpc/next, @prisma/client, and zod for validation. Run npx prisma init and configure your database URL in .env. Define a simple model, e.g., User with id, name, and email.
1. Create Your Prisma Client
In lib/prisma.ts, instantiate and export a singleton PrismaClient. This prevents multiple connections during development. Example:
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
export default prisma;
2. Build the tRPC Router
Create server/trpc.ts to initialize tRPC with a context that includes the Prisma client. Then define your procedures. For instance, a query that returns all users:
- Import
initTRPCandprisma. - Use
t.procedure.queryto callprisma.user.findMany(). - Add a mutation to create a user using
zodfor input validation.
3. Connect to Next.js API
In pages/api/trpc/[trpc].ts, export a tRPC HTTP handler. Pass your router and create context. This single endpoint handles all tRPC requests:
export default trpcNext.createNextApiHandler({
router: appRouter,
createContext: () => ({}),
});
4. Use tRPC Client on Frontend
Wrap your app with withTRPC HOC from @trpc/next. Inside a React component, call trpc.user.getAll.useQuery(). The data is typed perfectly. Mutations work similarly with useMutation.
That’s it! You now have a type‑safe pipeline from Prisma → tRPC → Next.js frontend. The server code stays minimal, and you can easily add more models and procedures without losing type safety.