Learn tRPC and Prisma Integration in Next.js 14 (app directory)

3 min read 4 hours ago
Published on Oct 15, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

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.

  1. Open your terminal.
  2. Run the following command to create a new Next.js app:
    npx create-next-app@latest my-app
    
  3. Navigate into your project directory:
    cd my-app
    

Step 2: Initialize tRPC

Now it's time to set up tRPC in your application.

  1. Install the necessary packages:
    npm install @trpc/server @trpc/client
    
  2. Create a new folder called trpc in the src directory for organizing your tRPC-related files.

Step 3: Set Up App Router

Configure the app router for handling API routes.

  1. Inside the trpc folder, create a file named appRouter.ts.
  2. 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
        },
      });
    
  3. 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.

  1. Open your _app.tsx file in the pages directory.
  2. 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.

  1. 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.

  1. Install Prisma and its dependencies:
    npm install prisma --save-dev
    npm install @prisma/client
    
  2. Initialize Prisma in your project:
    npx prisma init
    

Step 7: Define the Prisma Schema

Define your database schema in prisma/schema.prisma.

  1. 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.

  1. In your tRPC router, import Prisma client:
    import { PrismaClient } from '@prisma/client';
    const prisma = new PrismaClient();
    
  2. 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.

  1. 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.

  1. Start your application:
    npm run dev
    
  2. 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!