Learn tRPC and Prisma Integration in Next.js 14 (app directory)
Table of Contents
Introduction
In this tutorial, you will learn how to integrate tRPC and Prisma into your Next.js 14 application. This integration allows you to create custom user endpoints efficiently, enhancing the functionality of your full-stack application. Follow these step-by-step instructions to set up your project and start building robust features.
Step 1: Next.js Installation
To begin, you'll need to set up a new Next.js project.
- Open your terminal.
- Run the following command to create a new Next.js app:
npx create-next-app@latest my-app
- Navigate into your project directory:
cd my-app
Step 2: Initialize tRPC
Now it's time to set up tRPC in your application.
- Install the necessary packages:
npm install @trpc/server @trpc/client
- Create a new folder called
trpc
in thesrc
directory for organizing your tRPC-related files.
Step 3: Set Up App Router
Configure the app router for handling API routes.
- Inside the
trpc
folder, create a file namedappRouter.ts
. - Define your API routes by exporting a router instance:
import { createRouter } from '@trpc/server'; export const appRouter = createRouter() .query('getUser', { resolve() { // Logic to fetch user data }, });
- Set up your API handler in
pages/api/trpc/[trpc].ts
:import { createNextApiHandler } from '@trpc/server/adapters/next'; import { appRouter } from '../../../trpc/appRouter'; export default createNextApiHandler({ router: appRouter, createContext: () => ({}), });
Step 4: Implement the Provider
Add the tRPC provider to your application.
- Open your
_app.tsx
file in thepages
directory. - Wrap your application with the tRPC provider:
import { AppType } from 'next/app'; import { trpc } from '../trpc'; const MyApp: AppType = ({ Component, pageProps }) => { return ( <trpc.Provider> <Component {...pageProps} /> </trpc.Provider> ); }; export default MyApp;
Step 5: Conduct the First Test
Verify that your tRPC setup is working.
- Create a simple test query in a component:
const TestComponent = () => { const { data, error } = trpc.useQuery(['getUser']); if (error) return <div>Error loading user data</div>; return <div>User Data: {JSON.stringify(data)}</div>; };
Step 6: Initialize Prisma
Set up Prisma to manage your database.
- Install Prisma and its dependencies:
npm install prisma --save-dev npm install @prisma/client
- Initialize Prisma in your project:
npx prisma init
Step 7: Define the Prisma Schema
Define your database schema in prisma/schema.prisma
.
- Open
schema.prisma
and define your models:model User { id Int @id @default(autoincrement()) name String email String @unique }
Step 8: Make Prisma Database Calls
Implement database interactions using Prisma.
- In your tRPC router, import Prisma client:
import { PrismaClient } from '@prisma/client'; const prisma = new PrismaClient();
- Update your
getUser
query to fetch data from the database:.query('getUser', { resolve: async () => { return await prisma.user.findMany(); }, });
Step 9: Develop the Frontend
Create a frontend component to interact with your API.
- Build a component that displays user data:
const UserList = () => { const { data, error } = trpc.useQuery(['getUser']); if (error) return <div>Error loading users</div>; return ( <ul> {data.map(user => ( <li key={user.id}>{user.name}</li> ))} </ul> ); };
Step 10: Final Testing
Run your application to ensure everything is functioning correctly.
- Start your application:
npm run dev
- Navigate to
http://localhost:3000
to see your application in action.
Conclusion
You have successfully integrated tRPC and Prisma into your Next.js 14 application. This setup allows you to create custom user endpoints and manage database interactions with ease. Next steps could include exploring more complex queries or enhancing the frontend experience. Happy coding!