How to use prisma with postgres in next.js using migration
Step-by-Step Guide: Using Next.js with Prisma and PostgreSQL
This guide will walk you through setting up Prisma with Next.js and using PostgreSQL as the database. You will define your database schema in schema.prisma
and migrate it to PostgreSQL.
Step 1: Create a Next.js Project
If you don’t have a Next.js project yet, create one:
npx create-next-app@latest my-nextjs-app cd my-nextjs-app
Step 2: Install Prisma and PostgreSQL Client
Inside your Next.js project, install Prisma and the PostgreSQL driver:
npm install --save-dev prisma
npm install @prisma/client
npm install pg # PostgreSQL client
Step 3: Initialize Prisma
Run the following command to set up Prisma:
npx prisma init
This will create:
✅ A prisma/
folder containing schema.prisma
✅ A .env
file to store your database URL
Step 4: Configure PostgreSQL Connection
In your .env
file, update the DATABASE_URL with your PostgreSQL credentials:
DATABASE_URL="postgresql://USER:PASSWORD@localhost:5432/mydatabase"
- Replace USER and PASSWORD with your PostgreSQL credentials.
- Replace mydatabase with your database name.
- If PostgreSQL is running in Docker, the host should be
host.docker.internal
.
Step 5: Define Database Schema in schema.prisma
Open prisma/schema.prisma
and define a sample User
model:
generator client { provider = "prisma-client-js" } datasource db { provider = "postgresql" url = env("DATABASE_URL") } model User { id String @id @default(uuid()) name String email String @unique createdAt DateTime @default(now()) }
Step 6: Run Database Migration
Create a migration and apply it to the database:
npx prisma migrate dev --name init
This will:
✅ Create a migrations/
folder inside prisma/
.
✅ Apply the schema to PostgreSQL.
Step 7: Generate Prisma Client
After migrating, generate Prisma Client to interact with the database:
npx prisma generate
Step 8: Use Prisma in Next.js API Routes
Create a new API route at pages/api/users.js
:
import { PrismaClient } from "@prisma/client"; const prisma = new PrismaClient(); export default async function handler(req, res) { if (req.method === "GET") { const users = await prisma.user.findMany(); res.status(200).json(users); } else if (req.method === "POST") { const { name, email } = req.body; const newUser = await prisma.user.create({ data: { name, email }, }); res.status(201).json(newUser); } else { res.status(405).json({ message: "Method Not Allowed" }); } }
- GET
/api/users
→ Fetch all users - POST
/api/users
→ Add a new user
Step 9: Test the API
Start your Next.js app:
npm run dev
Use Postman or cURL to test the API:
- Get Users:
curl -X GET http://localhost:3000/api/users
- Create User:
curl -X POST http://localhost:3000/api/users \ -H "Content-Type: application/json" \ -d '{"name": "John Doe", "email": "john@example.com"}'
Step 10: Use Prisma in a Next.js Page
Modify pages/index.js
to fetch users from the database:
import { PrismaClient } from "@prisma/client"; const prisma = new PrismaClient(); export async function getServerSideProps() { const users = await prisma.user.findMany(); return { props: { users } }; } export default function Home({ users }) { return ( <div> <h1>Users</h1> <ul> {users.map((user) => ( <li key={user.id}>{user.name} - {user.email}</li> ))} </ul> </div> ); }
Step 11: Deploy (Optional)
When deploying your Next.js app (e.g., on Vercel, DigitalOcean, etc.), ensure you set the DATABASE_URL in the environment variables.
Run migrations in production:
npx prisma migrate deploy
Quick Summary
Step | Command |
---|---|
Create Next.js app | npx create-next-app my-nextjs-app |
Install Prisma & PostgreSQL client | npm install @prisma/client prisma pg |
Initialize Prisma | npx prisma init |
Configure .env | Set DATABASE_URL |
Define schema in schema.prisma | Update models |
Run migration | npx prisma migrate dev --name init |
Generate Prisma Client | npx prisma generate |
Run Next.js app | npm run dev |
Deploy migrations | npx prisma migrate deploy |
🎉 Done! Now you have Next.js with Prisma and PostgreSQL set up. Let me know if you need any modifications! 🚀