Best practice for instantiating PrismaClient with Next.js

Problem

Lots of users have come across this warning while working with Next.js in development:

warn(prisma-client) Already 10 Prisma Clients are actively running

There's a related discussion and issue for the same.

In development, the command next dev clears Node.js cache on run. This in turn initializes a new PrismaClient instance each time due to hot reloading that creates a connection to the database. This can quickly exhaust the database connections as each PrismaClient instance holds its own connection pool.

Solution

The solution in this case is to instantiate a single instance PrismaClient and save it on the global object. Then we keep a check to only instantiate PrismaClient if it's not on the global object otherwise use the same instance again if already present to prevent instantiating extra PrismaClient instances.

./db
1import { PrismaClient } from "@prisma/client";
2
3// add prisma to the NodeJS global type
4interface CustomNodeJsGlobal extends NodeJS.Global {
5 prisma: PrismaClient;
6}
7
8// Prevent multiple instances of Prisma Client in development
9declare const global: CustomNodeJsGlobal;
10
11const prisma = global.prisma || new PrismaClient();
12
13if (process.env.NODE_ENV === "development") global.prisma = prisma;
14
15export default prisma;

After creating this file, you can now import this PrismaClient instance anywhere in your Next.js pages as follows:

// e.g. in `pages/index.tsx`
import prisma from './db'
export const getServerSideProps = async ({ req }) => {
const token = req.headers.AUTHORIZATION
const userId = await getUserId(token)
const posts = await prisma.post.findMany({
where: {
author: { id: userId },
},
})
return { props: { posts } }
}
Edit this page on GitHub