04: Set Up Prisma with NeonDB#3
Conversation
📝 WalkthroughWalkthroughAdds Prisma PostgreSQL schema and migrations, configures the Prisma client, and introduces a Next.js API route that returns videos ordered by creation time. ChangesPrisma video API
Estimated code review effort: 3 (Moderate) | ~20 minutes Sequence Diagram(s)sequenceDiagram
participant VideoAPIClient
participant GETVideosRoute
participant PrismaClient
participant PostgreSQL
VideoAPIClient->>GETVideosRoute: GET /api/videos
GETVideosRoute->>PrismaClient: Query videos by createdAt descending
PrismaClient->>PostgreSQL: Read Video records
PostgreSQL-->>PrismaClient: Return video records
PrismaClient-->>GETVideosRoute: Return ordered videos
GETVideosRoute-->>VideoAPIClient: Return JSON response
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (2)
prisma/schema.prisma (1)
12-12: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUse camelCase for field names.
In Prisma, it is conventional to use camelCase for model fields. Consider renaming
Titletotitlefor consistency with the rest of the fields.♻️ Proposed refactor
- Title String + title String🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@prisma/schema.prisma` at line 12, Rename the Prisma model field Title to title in the schema, and update any references to that field to use the new camelCase name.prisma/migrations/20260716103931_init/migration.sql (1)
4-4: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueInconsistent capitalization for the
Titlecolumn.The column name
Titleis capitalized, whereas the other columns use camelCase or lowercase (e.g.,description,publicId). This will result in the generated Prisma client requiringvideo.Titleinstead of the conventionalvideo.title.Consider renaming this field to
titlein yourprisma/schema.prismafile and regenerating the migration to maintain consistent naming conventions.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@prisma/migrations/20260716103931_init/migration.sql` at line 4, Rename the Title field to title in the Prisma schema and regenerate the migration so the database column and generated Prisma client use the conventional lowercase name. Update references to the affected model field as needed while preserving its existing type and required constraint.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@app/api/videos/route.ts`:
- Around line 16-18: Remove the finally block and its prisma.$disconnect() call
from the route handler, leaving the existing request logic unchanged so the
shared Prisma client can manage its connection pool across requests.
In `@lib/prisma.ts`:
- Around line 7-8: Update the module-scope PrismaClient initialization around
PrismaPg and PrismaClient to store and reuse the client through a global
singleton, including across Next.js Fast Refresh reloads. Create the client only
when the global instance is absent, then expose that shared instance as prisma;
preserve the existing adapter configuration.
In `@package.json`:
- Around line 29-30: Move `@prisma/adapter-pg` and `@prisma/client` from
devDependencies into dependencies in package.json so runtime database processing
through lib/prisma.ts remains available in production installations. Leave the
prisma CLI in devDependencies.
---
Nitpick comments:
In `@prisma/migrations/20260716103931_init/migration.sql`:
- Line 4: Rename the Title field to title in the Prisma schema and regenerate
the migration so the database column and generated Prisma client use the
conventional lowercase name. Update references to the affected model field as
needed while preserving its existing type and required constraint.
In `@prisma/schema.prisma`:
- Line 12: Rename the Prisma model field Title to title in the schema, and
update any references to that field to use the new camelCase name.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 4ab7beaf-b389-445d-ae9a-a5e560c3d7c1
⛔ Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (10)
.gitignoreapp/api/videos/route.tslib/prisma.tspackage.jsonprisma.config.tsprisma/migrations/20260716103931_init/migration.sqlprisma/migrations/20260716105659_added_user_model/migration.sqlprisma/migrations/migration_lock.tomlprisma/schema.prismatsconfig.json
| } finally { | ||
| await prisma.$disconnect(); | ||
| } |
There was a problem hiding this comment.
🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win
Do not manually disconnect the Prisma client in route handlers.
Calling prisma.$disconnect() at the end of a request destroys the connection pool managed by the Prisma client. This forces subsequent requests to re-establish database connections, adding significant latency overhead and potentially causing connection churn or race conditions under load.
Prisma is designed to maintain a persistent connection pool across requests automatically. You should remove the finally block entirely and allow Prisma to manage the connections.
🛠 Proposed fix
- } finally {
- await prisma.$disconnect();
}
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| } finally { | |
| await prisma.$disconnect(); | |
| } | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@app/api/videos/route.ts` around lines 16 - 18, Remove the finally block and
its prisma.$disconnect() call from the route handler, leaving the existing
request logic unchanged so the shared Prisma client can manage its connection
pool across requests.
| const adapter = new PrismaPg({ connectionString }); | ||
| const prisma = new PrismaClient({ adapter }); |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Prevent database connection exhaustion in development.
In Next.js, instantiating the PrismaClient directly in module scope will create a new connection pool every time the module is reloaded during development (Fast Refresh). This quickly leads to database connection exhaustion errors.
Use a global singleton pattern to reuse the Prisma client instance across hot reloads.
🛠 Proposed fix
-const adapter = new PrismaPg({ connectionString });
-const prisma = new PrismaClient({ adapter });
+const globalForPrisma = globalThis as unknown as { prisma: PrismaClient };
+
+const prisma =
+ globalForPrisma.prisma ||
+ new PrismaClient({ adapter: new PrismaPg({ connectionString }) });
+
+if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const adapter = new PrismaPg({ connectionString }); | |
| const prisma = new PrismaClient({ adapter }); | |
| const globalForPrisma = globalThis as unknown as { prisma: PrismaClient }; | |
| const prisma = | |
| globalForPrisma.prisma || | |
| new PrismaClient({ adapter: new PrismaPg({ connectionString }) }); | |
| if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma; |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@lib/prisma.ts` around lines 7 - 8, Update the module-scope PrismaClient
initialization around PrismaPg and PrismaClient to store and reuse the client
through a global singleton, including across Next.js Fast Refresh reloads.
Create the client only when the global instance is absent, then expose that
shared instance as prisma; preserve the existing adapter configuration.
| "@prisma/adapter-pg": "^7.8.0", | ||
| "@prisma/client": "^7.8.0", |
There was a problem hiding this comment.
🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win
Move runtime Prisma packages to dependencies.
@prisma/client and @prisma/adapter-pg are required at runtime to process database requests in your API routes (as seen in lib/prisma.ts). By placing them in devDependencies, they will be pruned in standard production deployments (e.g., when installing with --production or --omit=dev), leading to application crashes.
Please move both @prisma/adapter-pg and @prisma/client to the dependencies block. The prisma CLI (line 38) can safely remain in devDependencies.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@package.json` around lines 29 - 30, Move `@prisma/adapter-pg` and
`@prisma/client` from devDependencies into dependencies in package.json so runtime
database processing through lib/prisma.ts remains available in production
installations. Leave the prisma CLI in devDependencies.
Adds Prisma configuration and schema and generates the Prisma client so the app can interact with the database with typed models.
Configures NeonDB as the target database via a DATABASE_URL environment variable and includes guidance to set that variable for local development.
Adds migration files / initial schema so the database can be created/migrated in a reproducible way.
Adds or updates npm scripts to run Prisma commands (migrate, generate) and includes brief instructions for testing locally.