Next.js Prisma: “PrismaClient is already running” error in development #177437
-
|
Hey everyone 👋 Error:
Invalid `prisma.user.findMany()` invocation:
PrismaClient is already running a query.Sometimes I also see: PrismaClient is unable to be run because it was already started.It happens randomly after saving files or hot reloading. import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
export default prisma;Any idea how to fix this during development? Guidelines
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
|
This happens because Next.js reloads modules frequently in dev mode, and every reload creates a new PrismaClient instance — which overloads the database connection pool. ✅ Fix: Here’s the recommended setup 👇 // lib/prisma.ts
import { PrismaClient } from "@prisma/client";
const globalForPrisma = global as unknown as { prisma: PrismaClient };
export const prisma =
globalForPrisma.prisma ||
new PrismaClient({
log: ["query"],
});
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
export default prisma;Then simply import in your code: import prisma from "@/lib/prisma";✅ This ensures:
|
Beta Was this translation helpful? Give feedback.
-
|
This usually happens in Next.js (App Router) because every time the dev server hot-reloads, it creates a new PrismaClient instance. After a few reloads, multiple clients exist and Prisma throws:
✅ Fix: Use a global Prisma client in developmentMake sure you only create one PrismaClient instance during // lib/prisma.ts
import { PrismaClient } from "@prisma/client";
const globalForPrisma = global as unknown as {
prisma: PrismaClient | undefined;
};
export const prisma =
globalForPrisma.prisma ??
new PrismaClient({
log: ["query", "error", "warn"],
});
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;Then import it everywhere: import { prisma } from "@/lib/prisma";Why this works
Extra tips
After switching to the global client pattern, the error should disappear. |
Beta Was this translation helpful? Give feedback.
This happens because Next.js reloads modules frequently in dev mode, and every reload creates a new PrismaClient instance — which overloads the database connection pool.
✅ Fix:
Use a singleton pattern so Prisma reuses the same client instead of reinitializing it on every reload.
Here’s the recommended setup 👇
Then simply import in your code: