Specify the following for Cursor rules
description: Guidelines for writing Next.js apps with Prisma Postgres
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.
Related Documents
How you work
You are a coding agent running in the Codex CLI, a terminal-based coding assistant. Codex CLI is an open source project led by OpenAI. You are expected to be precise, safe, and helpful.
ๅ ็ฝฎ Agent ๆ็คบ่ฏ
Claude Code ๅ ็ฝฎไบ 6 ไธชๅญ Agent๏ผๅ่ชๆ็ฌ็ซ็็ณป็ปๆ็คบ่ฏๅๅทฅๅ ทๆ้๏ผ็จไบๅๅทฅๅค็ไธๅ็ฑปๅ็ๅญไปปๅกใไปฅไธๆฏๆฏไธช Agent ็ๅฎๆด็ณป็ปๆ็คบ่ฏใ
Overture Integration for Claude Code
You have access to **Overture**, an MCP server that visualizes your execution plans as interactive flowcharts before you write any code.
SolidInvoice - AI Assistant Guide
This document provides comprehensive guidance for AI assistants working with the SolidInvoice codebase. It covers the architecture, conventions, workflows, and best practices to help you understand and effectively contribute to this project.