Instantiating the client
The following example demonstrates how to import and instantiate your generated client from the default path:
import { PrismaClient } from '@prisma/client'const prisma = new PrismaClient()// use `prisma` in your application to read and write data in your DB
PrismaClient
accepts parameters that determine:
Use a single shared instance of PrismaClient
In long-running applications, we recommend that you:
- ✔ Create one instance of
PrismaClient
and re-use it across your application - ✔ Assign
PrismaClient
to a global variable in dev environments only to prevent hot reloading from creating new instances
Note: You do not need to explicitly
$disconnect()
in the context of a long-running application, such as a GraphQL server.
Multiple instances of PrismaClient
results in multiple instances of the query engine. Each query engine creates a connection pool with a default pool size of num_physical_cpus * 2 + 1
. Too many connections may start to slow down your database and eventually lead to the following error:
Error in connector: Error querying the database: db error: FATAL: sorry, too many clients alreadyat PrismaClientFetcher.request
To re-use a single instance, create a module that exports a PrismaClient
object:
client.ts
1import { PrismaClient } from "@prisma/client"23let prisma = new PrismaClient()45export default prisma
The object is cached the first time the module is imported. Subsequent requests return the cached object rather than creating a new PrismaClient
:
app.ts
1import prisma from './client'23async function main() {4 const allUsers = await prisma.user.findMany();5}67main();
Prevent hot reloading from creating new instances of PrismaClient
Frameworks like Next.js support hot reloading of changed files, which enables you to see changes to your application without restarting. However, if the framework refreshes the module responsible for exporting PrismaClient
, this can result in additional, unwanted instances of PrismaClient
in a development environment.
As a workaround, you can store PrismaClient
as a global variable in development environments only, as global variables are not reloaded:
client.ts
1import { PrismaClient } from "@prisma/client"23declare global {4 namespace NodeJS {5 interface Global {6 prisma: PrismaClient;7 }8 }9}1011let prisma: PrismaClient;1213if (process.env.NODE_ENV === "production") {14 prisma = new PrismaClient()15} else {16 if (!global.prisma) {17 global.prisma = new PrismaClient()18 }1920 prisma = global.prisma21}2223export default prisma
The way that you import and use the client does not change:
app.ts
1import prisma from './client'23async function main() {4 const allUsers = await prisma.user.findMany();5}67main();