How to Resolve the Already 10 Prisma Clients are Actively Running Error
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:
Create a new file called
lib/prisma.jsin your Next.js project.Copy the following code into the
lib/prisma.jsfile:
1 | import { PrismaClient } from '@prisma/client' |
The
ifcondition checks if the environment is in production. If it is, a new instance ofPrismaClientis created. Otherwise, it checks if theglobal.prismaobject already exists and assigns it toprisma. If theglobal.prismaobject doesn’t exist, it creates a new instance and assigns it to bothglobal.prismaandprisma.Once you have exported the
prismaobject fromlib/prisma.js, you can import it into your pages like this:
1 | 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.