Prisma Next.js Guide

September 17, 2024 (4w ago)

Seamless Integration: Installing and Configuring Prisma in Next.js App Router

What is Prisma?

Prisma is an open-source database toolkit that simplifies database access and management in modern application development. It consists of three main tools:

  1. Prisma ORM: An object-relational mapping (ORM) tool for Node.js and TypeScript.
  2. Prisma Migrate: A declarative database schema migration system.
  3. Prisma Studio: A GUI for viewing and editing data in your database.

Prisma supports various databases, including PostgreSQL, MySQL, SQLite, and MongoDB, making it a versatile choice for developers.

Step-by-Step Guide to Installing Prisma in Next.js App Router

1. Install Next.js

First, create a new Next.js project with the App Router:

npx create-next-app@latest my-prisma-app
cd my-prisma-app

Follow the prompts, ensuring you select "Yes" for using the App Router.

2. Install Prisma

Now, let's install Prisma in your Next.js project:

npm install prisma --save-dev

This command installs Prisma CLI as a development dependency in your project.

3. Initialize Prisma

Run the following command to initialize Prisma in your project:

npx prisma init

This command does two important things:

  1. Creates a new prisma directory containing a schema.prisma file. This file is where you'll define your database schema and models.
  2. Creates a .env file in the root of your project. This file is used to store environment variables, including your database connection string.

4. Connect to Your Database

Open the prisma/schema.prisma file and update the datasource block to specify your database provider. For this example, we'll use PostgreSQL:

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

Next, open the .env file and update the DATABASE_URL environment variable with your database connection string:

DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public"

Replace johndoe, randompassword, localhost, 5432, and mydb with your actual database credentials and details.

5. Define Your Schema

In the schema.prisma file, define your data models. For example:

model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
  posts Post[]
}
 
model Post {
  id        Int     @id @default(autoincrement())
  title     String
  content   String?
  published Boolean @default(false)
  author    User    @relation(fields: [authorId], references: [id])
  authorId  Int
}

6. Generate Prisma Client

After defining your schema, generate Prisma Client:

npx prisma generate

This command creates a custom Prisma Client based on your schema.

7. Push Your Schema to the Database

To create the tables in your database based on your Prisma schema, run:

npx prisma db push

8. (Optional) Explore Your Data with Prisma Studio

To view and edit your data visually, you can use Prisma Studio:

npx prisma studio

This command starts Prisma Studio on http://localhost:5555.

Install and Generate Prisma Client

Prisma Client is an auto-generated database client that enables type-safe database access and reduces boilerplate code. To install it:

npm install @prisma/client

After installation, generate Prisma Client:

npx prisma generate

Setting Up Prisma Client in Next.js

Create a new directory and file for database operations:

mkdir lib && touch lib/db.ts

In lib/db.ts, paste the following code:

import { PrismaClient } from '@prisma/client';
 
const prismaClientSingleton = () => {
  return new PrismaClient();
};
 
declare const globalThis: {
  prismaGlobal: ReturnType<typeof prismaClientSingleton>;
} & typeof global;
 
const prisma = globalThis.prismaGlobal ?? prismaClientSingleton();
 
export default prisma;
 
if (process.env.NODE_ENV !== 'production') globalThis.prismaGlobal = prisma;

This code ensures that only one instance of PrismaClient is created and reused across your application, preventing the creation of multiple instances during development hot reloads. It creates a single PrismaClient instance and saves it on the globalThis object, reusing it if it already exists.

Using Prisma in Next.js App Router

Example: Server Component

In a server component (e.g., app/page.tsx):

import prisma from '../lib/db';
 
export default async function Home() {
  const users = await prisma.user.findMany();
 
  return (
    <main>
      <h1>Users</h1>
      <ul>
        {users.map((user) => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </main>
  );
}

Example: Client Component

For client components, you'll need to create an API route to fetch data. First, create an API route (e.g., app/api/users/route.ts):

import { NextResponse } from 'next/server';
import prisma from '../../../lib/db';
 
export async function GET() {
  const users = await prisma.user.findMany();
  return NextResponse.json(users);
}

Then, in your client component (e.g., app/client-component.tsx):

'use client';
 
import { useState, useEffect } from 'react';
 
export default function ClientComponent() {
  const [users, setUsers] = useState([]);
 
  useEffect(() => {
    async function fetchUsers() {
      const response = await fetch('/api/users');
      const data = await response.json();
      setUsers(data);
    }
    fetchUsers();
  }, []);
 
  return (
    <div>
      <h2>Users (Client Component)</h2>
      <ul>
        {users.map((user) => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
}

Remember to import and use this client component in a server component or page.

By following these steps, you'll have Prisma successfully integrated into your Next.js application with the App Router, allowing for efficient and type-safe database operations.