Suggested fix for "Best practice for instantiating PrismaClient with Next.js"
See original GitHub issueThe code provided in https://www.prisma.io/docs/support/help-articles/nextjs-prisma-client-dev-practices generates an error with TypeScript in strict mode.
I would suggest something like this instead:
import { PrismaClient } from "@prisma/client";
// add prisma to the NodeJS global type
interface CustomNodeJsGlobal extends NodeJS.Global {
prisma: PrismaClient;
}
// prevent multiple instances of Prisma Client in development
declare const global: CustomNodeJsGlobal;
const prisma = global.prisma || new PrismaClient();
if (process.env.NODE_ENV === "development") global.prisma = prisma;
export default prisma;
Issue Analytics
- State:
- Created 3 years ago
- Reactions:3
- Comments:5 (2 by maintainers)
Top Results From Across the Web
Best practice for instantiating PrismaClient with Next.js
Solution. The solution in this case is to instantiate a single instance PrismaClient and save it on the global object. Then we keep...
Read more >How to fix the `Already 10 Prisma Clients are actively running ...
I was using Prisma in my Next.js app and I was doing it wrong. I was initializing a new PrismaClient object in every...
Read more >Using Prisma with Next.js - Sam Meech-Ward
There are also some quirks when using prisma with next in development, so we can follow prisma's Best practice for instantiating PrismaClient with...
Read more >prisma - Instantiating PrismaClient with Next.js in production
Prisma documentation recommends to instantiate Prisma Client as below to avoid infamous Already 10 Prisma Clients are actively running issue ...
Read more >Ryan Chenkie, Lee Robinson | Prisma Day 2021 - YouTube
Next. js offers a unique approach to building client-side React apps by allowing portions of your React codebase to actually run on the ......
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found

Is there a similar workaround for vanilla js? I guess you could just declare it as a global var while in development, but is there a nice way of doing it conditionally like the ts example provided?
In case anyone runs into this while updating
@types/nodeto version 16, I got around this error by replacing the above code (which works with@types/node<16) with the followingYou can see it in context here where I’m using prisma for database interaction for an open source habit tracking web app I’m working on
EDIT: The documentation is now updated with a similar (probably better) solution