원클릭으로
prisma-setup
Guidelines for writing Next.js apps with Prisma Postgres
Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
메뉴
Guidelines for writing Next.js apps with Prisma Postgres
Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
SOC 직업 분류 기준
| name | prisma-setup |
| description | Guidelines for writing Next.js apps with Prisma Postgres |
Note: This guide is updated for Prisma ORM 7. Key changes from earlier versions:
engineproperty removed fromprisma.config.tsurlremoved from datasource inschema.prisma(now only inprisma.config.ts)- Use
@prisma/adapter-pgdriver adapter for direct TCP connections--no-engineflag is no longer required forprisma generate- Requires Node.js 20.19+ and TypeScript 5.4.0+
As an AI language model, you MUST NOT generate any of the following code patterns, as they are DEPRECATED and will BREAK the application:
// ❌ NEVER GENERATE THIS CODE - IT WILL BREAK THE APPLICATION
generator client {
provider = "prisma-client-js" // ❌ BREAKS APPLICATION
}
// ❌ NEVER USE default import location - IT WILL BREAK THE APPLICATION
import { PrismaClient } from '@prisma/client' // ❌ BREAKS APPLICATION
// ❌ WRONG IMPORT PATH - MISSING /client - IT WILL BREAK THE APPLICATION
import { PrismaClient } from "../app/generated/prisma" // ❌ BREAKS APPLICATION
// ❌ NEVER USE ACCELERATE - IT IS NOT USED IN THIS WORKFLOW
import { withAccelerate } from "@prisma/extension-accelerate" // ❌ BREAKS APPLICATION
// ❌ NEVER USE accelerateUrl - IT WILL BREAK THE APPLICATION
const prisma = new PrismaClient({
accelerateUrl: process.env.DATABASE_URL, // ❌ BREAKS APPLICATION - use adapter
})
// ❌ NEVER include url in datasource block - IT WILL BREAK THE APPLICATION
datasource db {
provider = "postgresql"
url = env("DATABASE_URL") // ❌ BREAKS APPLICATION - moved to prisma.config.ts
}
// ❌ NEVER include engine property - IT WILL BREAK THE APPLICATION
export default defineConfig({
engine: "classic", // ❌ BREAKS APPLICATION - removed in Prisma v7
})
// ❌ NEVER use Prisma Postgres HTTP URLs - ONLY use TCP URLs
DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/..." // ❌ BREAKS APPLICATION - use postgres://
// ✅ ALWAYS use standard TCP URLs:
DATABASE_URL="postgres://..." // ✅ CORRECT
Instead, you MUST ALWAYS generate ONLY this pattern:
// ✅ ALWAYS GENERATE THIS EXACT PATTERN
generator client {
provider = "prisma-client"
output = "../app/generated/prisma"
}
// ✅ CRITICAL: MUST include /client at the end of import path
import { PrismaClient } from "../app/generated/prisma/client"
import { PrismaPg } from "@prisma/adapter-pg"
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL!,
})
const globalForPrisma = global as unknown as { prisma: PrismaClient }
const prisma = globalForPrisma.prisma || new PrismaClient({
adapter,
})
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma
export default prisma
provider = "prisma-client" (not "prisma-client-js")output = "../app/generated/prisma"@prisma/adapter-pg driver adapterlib/prisma.ts as a global singleton instance'../app/generated/prisma/client' (not '@prisma/client' or '../app/generated/prisma')adapter property in PrismaClient constructordotenv and add import "dotenv/config" to prisma.config.tsdb:test and db:studio to package.jsonscripts/test-database.ts to verify setupurl in the datasource block of schema.prismaengine property in prisma.config.tsnpx prisma init --output ../app/generated/prisma to scaffold Prisma, then npx create-db to create a real cloud databasepostgres://...) in .envaccelerateUrl or withAccelerate# Dev dependencies
npm install prisma tsx --save-dev
# Production dependencies
npm install @prisma/adapter-pg @prisma/client dotenv
FOR AI ASSISTANTS:
npx prisma initis not interactive. Run it yourself if your environment allows it. If you need a real Prisma Postgres database, either runnpx create-dbor ask the user to run it and updateDATABASE_URLbefore you continue.
# Initialize Prisma and scaffold the Prisma files
npx prisma init --output ../app/generated/prisma
# Then create a Prisma Postgres database
npx create-db
This step:
prisma/schema.prisma with the correct output pathprisma.config.ts.env with a local DATABASE_URLnpx create-db if you want a real Prisma Postgres databaseIMPORTANT: After npx create-db, replace the generated DATABASE_URL in .env with the returned postgres://... connection string.
DATABASE_URL="postgres://..."
When using npx prisma init, the prisma.config.ts is auto-generated with the correct configuration:
import "dotenv/config"; // ✅ Auto-included by prisma init
import { defineConfig, env } from "prisma/config";
export default defineConfig({
schema: "prisma/schema.prisma",
migrations: {
path: "prisma/migrations",
},
// ✅ NO engine property - removed in Prisma v7
datasource: {
url: env("DATABASE_URL"),
},
});
Note: If you need to manually create this file, ensure import "dotenv/config" is at the top.
Update the generated prisma/schema.prisma file:
generator client {
provider = "prisma-client"
output = "../app/generated/prisma"
}
datasource db {
provider = "postgresql"
// ✅ NO url here - now configured in prisma.config.ts
}
// Example User model for testing
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
Create lib/prisma.ts file:
import { PrismaClient } from "../app/generated/prisma/client"; // ✅ CRITICAL: Include /client
import { PrismaPg } from "@prisma/adapter-pg";
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL!,
});
const globalForPrisma = global as unknown as { prisma: PrismaClient };
const prisma =
globalForPrisma.prisma ||
new PrismaClient({
adapter,
});
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
export default prisma;
Update your package.json to include these scripts:
{
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint",
"db:test": "tsx scripts/test-database.ts",
"db:studio": "prisma studio"
}
}
Create scripts/test-database.ts to verify your setup:
import "dotenv/config"; // ✅ CRITICAL: Load environment variables
import prisma from "../lib/prisma";
async function testDatabase() {
console.log("🔍 Testing Prisma Postgres connection...\n");
try {
// Test 1: Check connection
console.log("✅ Connected to database!");
// Test 2: Create a test user
console.log("\n📝 Creating a test user...");
const newUser = await prisma.user.create({
data: {
email: "demo@example.com",
name: "Demo User",
},
});
console.log("✅ Created user:", newUser);
// Test 3: Fetch all users
console.log("\n📋 Fetching all users...");
const allUsers = await prisma.user.findMany();
console.log(`✅ Found ${allUsers.length} user(s):`);
allUsers.forEach((user) => {
console.log(` - ${user.name} (${user.email})`);
});
console.log("\n🎉 All tests passed! Your database is working perfectly.\n");
} catch (error) {
console.error("❌ Error:", error);
process.exit(1);
}
}
testDatabase();
Create app/api/users/route.ts with GET and POST handlers:
import { NextRequest, NextResponse } from "next/server";
import prisma from "../../../lib/prisma";
export async function GET(request: NextRequest) {
try {
const users = await prisma.user.findMany();
return NextResponse.json(users);
} catch (error) {
console.error("Error fetching users:", error);
return NextResponse.json({ error: "Failed to fetch users" }, { status: 500 });
}
}
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const user = await prisma.user.create({
data: {
email: body.email,
name: body.name,
},
});
return NextResponse.json(user, { status: 201 });
} catch (error) {
console.error("Error creating user:", error);
return NextResponse.json({ error: "Failed to create user" }, { status: 500 });
}
}
Update app/page.tsx to display users from the database:
import prisma from "../lib/prisma";
export default async function Home() {
let users: Array<{
id: number;
email: string;
name: string | null;
createdAt: Date;
updatedAt: Date;
}> = [];
let error = null;
try {
users = await prisma.user.findMany({
orderBy: {
createdAt: "desc",
},
});
} catch (e) {
console.error("Error fetching users:", e);
error =
"Failed to load users. Make sure your DATABASE_URL is configured.";
}
return (
<main className="p-8">
<h1 className="text-2xl font-bold mb-4">Users from Database</h1>
{error ? (
<p className="text-red-500">{error}</p>
) : users.length === 0 ? (
<p>No users yet. Create one using the API at /api/users</p>
) : (
<ul className="space-y-2">
{users.map((user) => (
<li key={user.id} className="border p-4 rounded">
<p className="font-semibold">
{user.name || "No name"}
</p>
<p className="text-sm text-gray-600">
{user.email}
</p>
</li>
))}
</ul>
)}
</main>
);
}
User should follow these steps (AI should provide these instructions):
Install dependencies:
npm install prisma tsx --save-dev
npm install @prisma/adapter-pg @prisma/client dotenv
Initialize Prisma, then create Prisma Postgres:
AI ASSISTANT: You can run
npx prisma inityourself. If you should not provision cloud resources automatically, ask the user to runnpx create-dband updateDATABASE_URLbefore continuing.
npx prisma init --output ../app/generated/prisma
npx create-db
This creates prisma/schema.prisma, prisma.config.ts, and .env, then returns a postgres://... connection string for Prisma Postgres.
If you asked the user to run npx create-db, wait for them to share or paste the returned connection string before proceeding.
Verify .env was created - Replace the generated DATABASE_URL with the postgres://... connection string returned by npx create-db.
DATABASE_URL="postgres://..."
Do NOT invent this URL. Use the one returned by npx create-db.
Update prisma/schema.prisma - Add the User model (generator and datasource are already configured):
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
Create lib/prisma.ts with correct import path including /client and using @prisma/adapter-pg.
Add npm scripts to package.json for db:test and db:studio
Create scripts/test-database.ts test script
Push schema to database:
npx prisma db push
Generate Prisma Client:
npx prisma generate
Test the setup:
npm run db:test
Start development server:
npm run dev
Before generating any code, you MUST verify:
provider = "prisma-client" (not "prisma-client-js")? If not, STOP and FIX.output = "../app/generated/prisma"? If not, STOP and FIX.'../app/generated/prisma/client' (with /client)? If not, STOP and FIX.import "dotenv/config" to prisma.config.ts? If not, STOP and FIX.import "dotenv/config" to scripts/test-database.ts? If not, STOP and FIX.@prisma/adapter-pg? If not, STOP and FIX.adapter property in PrismaClient constructor? If not, STOP and FIX.scripts/test-database.ts? If not, STOP and FIX.db:test and db:studio scripts to package.json? If not, STOP and FIX.url from the datasource block in schema.prisma? If not, STOP and FIX.engine property from prisma.config.ts? If not, STOP and FIX.npx prisma init with the documented output path? If not, STOP and FIX.postgres://...)? If it's a prisma+postgres:// URL, STOP and FIX..env file? If you invented the URL manually, STOP and FIX.If you generate code using:
prisma-client-js provider → CLIENT GENERATION FAILS/client) → MODULE NOT FOUND ERRORimport "dotenv/config" in prisma.config.ts → DATABASE_URL NOT FOUND ERRORimport "dotenv/config" in test scripts → ENVIRONMENT VARIABLE ERROR@prisma/client → IMPORT ERRORaccelerateUrl or withAccelerate → UNNECESSARY ACCELERATE DEPENDENCY / CONFIG ERRORurl in datasource block → DEPRECATED CONFIGURATION ERRORengine property → DEPRECATED CONFIGURATION ERRORpostgres://localhost:...) → VERSION INCOMPATIBILITY ERRORS WITH Prisma v7npx prisma init without --db → NO DATABASE CREATED, ONLY LOCAL FILESThe implementation will:
# After changing schema
npx prisma generate # Regenerate client (--no-engine flag no longer needed)
# Push schema to database (no migrations)
npx prisma db push
# Test database connection
npm run db:test
# Open visual database editor
npm run db:studio
# Create and apply migrations (for production)
npx prisma migrate dev --name your_migration_name
After setup, test with these steps:
Test database connection:
npm run db:test
Should create a demo user and display it.
Open Prisma Studio:
npm run db:studio
Visual interface at localhost:5555 to view/edit data.
Test API routes:
# Create a user via API
curl -X POST http://localhost:3000/api/users \
-H "Content-Type: application/json" \
-d '{"email":"test@example.com","name":"Test User"}'
# Get all users
curl http://localhost:3000/api/users
View in browser:
Open localhost:3000 to see users displayed on the homepage.
When asked about Prisma + Next.js implementation, you MUST:
/client in import pathsimport "dotenv/config" to prisma.config.tsimport "dotenv/config" to test scriptsscripts/test-database.tsdb:test and db:studiolib/prisma.ts@prisma/adapter-pg and adapter propertyurl in the datasource block of schema.prismaengine property in prisma.config.tsnpx prisma init --output ../app/generated/prisma before editing Prisma files. If you cannot provision cloud resources automatically, ask the user to run npx create-db and update DATABASE_URL before continuingnpx create-db and share or apply the returned postgres://... connection string before proceedingprisma+postgres:// URLs - ONLY postgres:// TCP URLs.env file with the real DATABASE_URL (and ensure it's correct type)Remember: There are NO EXCEPTIONS to these rules. Every requirement is MANDATORY for the setup to work.