Fix 'Already 10 Prisma Clients are actively running'
By Flavio Copes
Fix the Next.js Already 10 Prisma Clients are actively running error by exporting one shared PrismaClient instance from lib/prisma.js and reusing it.
The Already 10 Prisma Clients are actively running error means your Next.js app keeps creating new PrismaClient instances instead of reusing one. The fix is a single shared instance, exported from one file.
I was using Prisma in my Next.js app and I was doing it wrong.
I was initializing a new PrismaClient object in every page:
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
After some point, during app usage, I received the error Already 10 Prisma Clients are actively running and also a Address already in use.
Why does this happen?
Each PrismaClient instance opens its own pool of connections to the database. One instance is all an app needs.
In development, hot reloading makes things worse. Every time you save a file, npm run dev clears the Node.js module cache and re-runs your code. Each reload created a brand new PrismaClient, while the old ones stayed alive holding their connections. After enough saves, Prisma refused to start another one.
The fix: one shared instance
To fix this, I exported the Prisma initialization to a separate file, lib/prisma.js:
import { PrismaClient } from '@prisma/client'
let prisma
if (process.env.NODE_ENV === 'production') {
prisma = new PrismaClient()
} else {
if (!global.prisma) {
global.prisma = new PrismaClient()
}
prisma = global.prisma
}
export default prisma
In production the first branch runs. The module is only loaded once, so creating the client at module level is enough.
In development we store the instance on the global object instead. global survives hot reloads, while module-level variables don’t. On the next reload the code finds the existing client and reuses it, instead of creating client number eleven.
I took this code from https://www.prisma.io/docs/support/help-articles/nextjs-prisma-client-dev-practices
Finally I imported the exported prisma object in my pages:
import prisma from 'lib/prisma'
One thing to watch for
The fix only works if every file imports from lib/prisma.js. If a single API route still calls new PrismaClient() on its own, that route keeps leaking connections, and the error comes back.
Search your project for new PrismaClient and make sure it appears exactly once, inside lib/prisma.js.
Related posts about next: