Introduction
Prisma ORM is a powerful and type-safe database toolkit for Node.js and TypeScript. It simplifies database access and management, making it a great choice for Next.js applications. This guide will walk you through setting up Prisma with Next.js 15, TypeScript, and a PostgreSQL database.
Prerequisites
Ensure you have the following installed:
- Node.js (v16+)
- PostgreSQL
- npm or yarn
Step 1: Setting Up Next.js 15 Project
First, create a new Next.js 15 project with TypeScript:
npx create-next-app@latest my-prisma-app --typescript
cd my-prisma-app
Step 2: Installing Prisma and PostgreSQL Driver
Install Prisma and the PostgreSQL client library:
npm install @prisma/client
npm install --save-dev prisma
npm install pg
Step 3: Initializing Prisma
Run the following command to initialize Prisma:
npx prisma init
This command:
- Creates a
prisma
directory with aschema.prisma
file - Generates an
.env
file for database configuration
Step 4: Configuring PostgreSQL Connection
In the .env
file, update the database URL:
DATABASE_URL="postgresql://USER:PASSWORD@localhost:5432/DATABASE_NAME"
Replace USER
, PASSWORD
, and DATABASE_NAME
with your PostgreSQL credentials.
Step 5: Defining the Prisma Schema
Edit prisma/schema.prisma
to define a model:
model User {
id String @id @default(uuid())
name String
email String @unique
posts Post[]
}
model Post {
id String @id @default(uuid())
title String
content String?
author User @relation(fields: [authorId], references: [id])
authorId String
createdAt DateTime @default(now())
}
Step 6: Running Migrations
Generate and apply migrations:
npx prisma migrate dev --name init
This will create the database tables.
Step 7: Generating Prisma Client
Run the following command to generate the Prisma Client:
npx prisma generate
This command creates TypeScript types for your database models.
Step 8: Using Prisma in Next.js API Route
Create an API route in pages/api/users.ts
:
import { NextApiRequest, NextApiResponse } from 'next';
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === 'GET') {
const users = await prisma.user.findMany();
return res.status(200).json(users);
}
}
Step 9: Seeding the Database (Optional)
Add a prisma/seed.ts
file:
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
async function main() {
await prisma.user.create({
data: {
name: 'John Doe',
email: 'johndoe@example.com',
},
});
}
main()
.catch((e) => console.error(e))
.finally(async () => await prisma.$disconnect());
Run the seed command:
npx prisma db seed
Step 10: Prisma Studio (GUI for DB Management)
Launch Prisma Studio:
npx prisma studio
This opens a web interface to interact with your database.
List of Prisma Commands
Command | Description |
---|---|
npx prisma init |
Initializes Prisma in the project. |
npx prisma migrate dev --name init |
Creates and applies a new migration. |
npx prisma generate |
Generates the Prisma client for TypeScript. |
npx prisma studio |
Opens Prisma Studio for database management. |
npx prisma db seed |
Runs the seed script to populate the database. |
npx prisma migrate status |
Shows the current migration status. |
npx prisma format |
Formats the Prisma schema file. |
npx prisma validate |
Validates the Prisma schema file. |
Conclusion
You have successfully set up Prisma ORM with Next.js 15, TypeScript, and PostgreSQL. This setup allows you to interact with your database using a fully typed API, making development more efficient and secure.
Top comments (0)