DEV Community

Cover image for How to fix Warning: 10 Prisma Clients are already running
Luis Juarez
Luis Juarez

Posted on

How to fix Warning: 10 Prisma Clients are already running

The first time I ran into this error, I thought I was doing something wrong. But as I dug into it a bit more, I realized this is a side-effect of javascript frameworks that rebuild the project anytime code changes.

warn(prisma-client) There are already 10 instances of Prisma Client actively running.
Enter fullscreen mode Exit fullscreen mode

The problem is that every time the code changes, a new connection is made to the database because new PrismaClient() is called.

To avoid a new connection being created during development every time a change is made, you can do a quick check to see if there is already a connection made, and if so, use that. If not, then call new PrismaClient().

Here is what that would look like:

File: ./util/db.server.js

import { PrismaClient } from '@prisma/client'

let db;

//check if we are running in production mode
if (process.env.NODE_ENV === 'production') {
  db = new PrismaClient()
} else {
//check if there is already a connection to the database
  if (!global.db) {
    global.db = new PrismaClient()
  }
  db = global.db
}

export { db };
Enter fullscreen mode Exit fullscreen mode

Now we are able to use the exported prisma object in our other components with:

import { db } from './util/db.server.js'

const data = db.user.findMany();
Enter fullscreen mode Exit fullscreen mode

And there you have it! Now your app will check if a connection to the database exists before creating a new one and you won't get that error message.

One last thing I should mention is that technically creating a new PrismaClient() isn't the issue, but the fact that Prisma objects call their own connect() method when they are first used (under the hood). This is called lazy connect. You can learn more about that here

Top comments (1)

Collapse
 
oarthurcandido profile image
Arthur Candido • Edited

Your post helped me to find the problem, thanks! Just to reinforce, all prisma.client imports need to use this "middleware" after creating it, i was already using this solution in my routes, but not in the auth route and this was breaking the app.