0
0
NextJSframework~8 mins

Prisma ORM setup in NextJS - Performance & Optimization

Choose your learning style9 modes available
Performance: Prisma ORM setup
MEDIUM IMPACT
This affects the initial server response time and database query efficiency in your Next.js app.
Setting up Prisma client in a Next.js API route
NextJS
import { PrismaClient } from '@prisma/client';

let prisma;

if (!global.prisma) {
  global.prisma = new PrismaClient();
}
prisma = global.prisma;

export default async function handler(req, res) {
  const users = await prisma.user.findMany();
  res.json(users);
}
Reuses a single PrismaClient instance across requests, reducing connection overhead and improving response speed.
📈 Performance GainSingle database connection pool reused, lowering latency and resource consumption.
Setting up Prisma client in a Next.js API route
NextJS
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();

export default async function handler(req, res) {
  const users = await prisma.user.findMany();
  res.json(users);
}
Creating a new PrismaClient instance on every API call causes extra overhead and can exhaust database connections.
📉 Performance CostTriggers multiple database connection setups, increasing server response time and resource usage.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
New PrismaClient per requestN/A (server-side)N/AN/A[X] Bad
Singleton PrismaClient instanceN/A (server-side)N/AN/A[OK] Good
Rendering Pipeline
Prisma ORM setup affects the server-side data fetching stage before rendering the page. Efficient client reuse reduces server processing time, improving the Largest Contentful Paint (LCP).
Server Data Fetching
Server Response
Client Rendering
⚠️ BottleneckDatabase connection setup and query execution
Core Web Vital Affected
LCP
This affects the initial server response time and database query efficiency in your Next.js app.
Optimization Tips
1Reuse PrismaClient instance to avoid repeated database connection overhead.
2Avoid creating PrismaClient inside API handlers directly to prevent resource exhaustion.
3Monitor server response times to catch slow database queries affecting LCP.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance issue when creating a new PrismaClient instance on every API request?
AIt increases client-side rendering time.
BIt causes repeated database connection setups increasing response time.
CIt causes excessive DOM reflows.
DIt blocks CSS from loading.
DevTools: Network
How to check: Open DevTools, go to Network tab, reload the page or API call, and check the server response time for data fetching requests.
What to look for: Look for longer server response times indicating slow database queries or connection overhead.