If you are using Prisma in your Next.js app and encountering the Already 10 Prisma Clients are actively running error, this blog post is for you. In this article, we will discuss the cause of this issue and provide a solution to fix it.

The Problem

The error Already 10 Prisma Clients are actively running occurs when you initialize a new PrismaClient object on every page of your Next.js app. This can lead to an excessive number of Prisma clients running simultaneously, causing conflicts and disruptive behavior.

The Solution

To resolve this issue, we recommend exporting the Prisma initialization to a separate file called lib/prisma.js. This ensures that only one instance of the PrismaClient is created and shared across all pages.

Here’s how you can implement the solution:

  1. Create a new file called lib/prisma.js in your Next.js project.

  2. Copy the following code into the lib/prisma.js file:

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
  1. The if condition checks if the environment is in production. If it is, a new instance of PrismaClient is created. Otherwise, it checks if the global.prisma object already exists and assigns it to prisma. If the global.prisma object doesn’t exist, it creates a new instance and assigns it to both global.prisma and prisma.

  2. Once you have exported the prisma object from lib/prisma.js, you can import it into your pages like this:

import prisma from 'lib/prisma'

By following these steps, you will ensure that only one instance of PrismaClient is running, preventing conflicts and eliminating the Already 10 Prisma Clients are actively running error.

For more details and best practices, you can refer to the official Prisma documentation on Next.js Prisma Client Dev Practices.

Tags: Prisma, Next.js, error handling, PrismaClient, Node.js