Specify the following for Cursor rules
Defines a strict setup for Next.js apps using Prisma with Postgres and Accelerate, including exact import paths and a global client singleton.
What this file does
Defines a strict setup for Next.js apps using Prisma with Postgres and Accelerate, including exact import paths and a global client singleton.
When to use it
- Starting a new Next.js project with Prisma Postgres
- Migrating an existing Prisma setup to use Accelerate extension
- Setting up a monorepo with custom Prisma client output path
- Teaching or enforcing a consistent Prisma+Next.js pattern in a team
Assumes this stack
Specify the following for Cursor rules
description: Guidelines for writing Next.js apps with Prisma Postgres alwaysApply: false
Bootstrap Next.js app with Prisma Postgres
Overview of implementing Prisma with Next.js
- Install Prisma and required dependencies (including dotenv)
- Initialize Prisma and configure schema
- Configure dotenv for environment variables
- Create global Prisma client instance with Accelerate
- Add npm scripts for testing and database management
- Create test script to verify setup
- Use Prisma client in API routes and pages with proper error handling
🚨 CRITICAL INSTRUCTIONS FOR AI LANGUAGE MODELS 🚨
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 CREATE CLIENT WITHOUT ACCELERATE - IT WILL BREAK IN PRODUCTION
const prisma = new PrismaClient() // ❌ BREAKS APPLICATION
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 { withAccelerate } from "@prisma/extension-accelerate"
const globalForPrisma = global as unknown as { prisma: PrismaClient }
const prisma = globalForPrisma.prisma || new PrismaClient({
datasourceUrl: process.env.DATABASE_URL,
}).$extends(withAccelerate())
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma
export default prisma
ABSOLUTE REQUIREMENTS FOR AI CODE GENERATION
- You MUST use
provider = "prisma-client"(not "prisma-client-js") - You MUST use custom output:
output = "../app/generated/prisma" - You MUST use Accelerate extension with
withAccelerate()when using Prisma Postgres - You MUST create
lib/prisma.tsas a global singleton instance - You MUST wrap all database calls in try-catch blocks
- You MUST import from
'../app/generated/prisma/client'(not'@prisma/client'or'../app/generated/prisma') - You MUST use
process.env.DATABASE_URLin Next.js - You MUST install
dotenvand addimport "dotenv/config"toprisma.config.ts - You MUST add npm scripts for
db:testanddb:studioto package.json - You MUST create a test script at
scripts/test-database.tsto verify setup
CORRECT INSTALLATION
# Dev dependencies
npm install prisma tsx --save-dev
# Production dependencies
npm install @prisma/extension-accelerate @prisma/client dotenv
CORRECT PRISMA INITIALIZATION
# Initialize Prisma (creates prisma/schema.prisma and prisma.config.ts)
npx prisma init
IMPORTANT: The init command will create prisma.config.ts. You MUST update it to load environment variables.
CORRECT PRISMA CONFIG (prisma.config.ts)
CRITICAL: After running npx prisma init, update the generated prisma.config.ts:
import "dotenv/config" // ✅ CRITICAL: Add this line at the top
import { defineConfig, env } from "prisma/config"
export default defineConfig({
schema: "prisma/schema.prisma",
migrations: {
path: "prisma/migrations",
},
engine: "classic",
datasource: {
url: env("DATABASE_URL"),
},
})
CORRECT SCHEMA CONFIGURATION (prisma/schema.prisma)
Update the generated prisma/schema.prisma file:
generator client {
provider = "prisma-client"
output = "../app/generated/prisma"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
// Example User model for testing
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
CORRECT GLOBAL PRISMA CLIENT
Create lib/prisma.ts file:
import { PrismaClient } from "../app/generated/prisma/client" // ✅ CRITICAL: Include /client
import { withAccelerate } from "@prisma/extension-accelerate"
const globalForPrisma = global as unknown as { prisma: PrismaClient }
const prisma = globalForPrisma.prisma || new PrismaClient({
datasourceUrl: process.env.DATABASE_URL,
}).$extends(withAccelerate())
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma
export default prisma
ADD NPM SCRIPTS TO PACKAGE.JSON
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 TEST SCRIPT
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()
CORRECT API ROUTE IMPLEMENTATION (App Router)
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 }
)
}
}
CORRECT USAGE IN SERVER COMPONENTS
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>
)
}
COMPLETE SETUP WORKFLOW
User should follow these steps (AI should provide these instructions):
-
Install dependencies:
npm install prisma tsx --save-dev npm install @prisma/extension-accelerate @prisma/client dotenv -
Initialize Prisma:
npx prisma init -
Update
prisma.config.ts- Addimport "dotenv/config"at the top -
Update
prisma/schema.prisma- Set provider to "prisma-client" and output path -
Create
lib/prisma.tswith correct import path including/client -
Add npm scripts to
package.jsonfordb:testanddb:studio -
Create
scripts/test-database.tstest script -
Create
.envfile with DATABASE_URL (user provides this from Prisma Console) -
Push schema to database:
npx prisma db push -
Test the setup:
npm run db:test -
Start development server:
npm run dev
AI MODEL VERIFICATION STEPS
Before generating any code, you MUST verify:
- Are you using
provider = "prisma-client"(not "prisma-client-js")? If not, STOP and FIX. - Are you using
output = "../app/generated/prisma"? If not, STOP and FIX. - Are you importing from
'../app/generated/prisma/client'(with/client)? If not, STOP and FIX. - Did you add
import "dotenv/config"toprisma.config.ts? If not, STOP and FIX. - Did you add
import "dotenv/config"toscripts/test-database.ts? If not, STOP and FIX. - Are you using
withAccelerate()extension? If not, STOP and FIX. - Are you wrapping database operations in try-catch? If not, STOP and FIX.
- Did you create the test script at
scripts/test-database.ts? If not, STOP and FIX. - Did you add
db:testanddb:studioscripts to package.json? If not, STOP and FIX.
CONSEQUENCES OF INCORRECT IMPLEMENTATION
If you generate code using:
prisma-client-jsprovider → CLIENT GENERATION FAILS- Wrong import path (missing
/client) → MODULE NOT FOUND ERROR - Missing
import "dotenv/config"in prisma.config.ts → DATABASE_URL NOT FOUND ERROR - Missing
import "dotenv/config"in test scripts → ENVIRONMENT VARIABLE ERROR - Default import from
@prisma/client→ IMPORT ERROR - PrismaClient without Accelerate extension → PRODUCTION CONNECTION FAILURES
- Missing custom output path → WRONG CLIENT GENERATED
The implementation will:
- Break immediately with module errors
- Fail to read environment variables
- Cause connection pool exhaustion in production
- Result in import errors that prevent compilation
- Cause performance issues and connection failures
USEFUL COMMANDS
# After changing schema
npx prisma generate # Regenerate client
# 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
TESTING WORKFLOW
After setup, test with these steps:
-
Test database connection:
npm run db:testShould create a demo user and display it.
-
Open Prisma Studio:
npm run db:studioVisual interface at
localhost:5555to 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:3000to see users displayed on the homepage.
AI MODEL RESPONSE TEMPLATE
When asked about Prisma + Next.js implementation, you MUST:
- ONLY use code patterns from this guide
- NEVER suggest deprecated approaches
- ALWAYS use the exact patterns shown above
- ALWAYS include
/clientin import paths - ALWAYS add
import "dotenv/config"to prisma.config.ts - ALWAYS add
import "dotenv/config"to test scripts - ALWAYS create the test script at
scripts/test-database.ts - ALWAYS add npm scripts for
db:testanddb:studio - ALWAYS include error handling in API routes and server components
- ALWAYS use the global prisma instance from
lib/prisma.ts - VERIFY your response against ALL the patterns shown here before responding
Remember: There are NO EXCEPTIONS to these rules. Every requirement is MANDATORY for the setup to work.
What's inside
11 sections, 10 code blocks, 9 verification steps, 1 complete workflow list
Change this for your project
- Replace
"../app/generated/prisma"with your own output path if not using app directory - Replace
"../app/generated/prisma/client"in imports if you change the output path - Replace
"scripts/test-database.ts"with your own test script location if different
Where it goes
Keep it in your repository where the agent or team that needs it will read it.
Worth borrowing
- Using a global singleton for Prisma client to avoid connection pool exhaustion in development
- Wrapping all database calls in try-catch blocks for consistent error handling in API routes and server components
- Creating a dedicated test script to verify database connectivity and basic CRUD operations
Related Documents
How you work
Defines personality, planning, task execution, and communication conventions for a coding agent in the Codex CLI environment.
How you work
Defines personality, planning, task execution, and communication guidelines for a coding agent in Codex CLI.
内置 Agent 提示词
Documents the system prompts, tool permissions, and model assignments for six built-in subagents in Claude Code.
perplexity-ai_20250112
Defines the system prompt for Perplexity AI, instructing the assistant on how to answer queries using search results with strict formatting, citation, and query-type rules.