next-prisma-plugin
next-prisma-plugin copied to clipboard
Need to also clear `global.prisma` and `globalThis.prisma`
According to https://github.com/prisma/prisma-client-js/issues/228#issuecomment-618433162, we must use the below code in next.js environments to prevent the too many connections error.
import { PrismaClient } from "@prisma/client"
export * from "@prisma/client"
let prisma: PrismaClient
if (process.env.NODE_ENV === "production") {
prisma = new PrismaClient()
} else {
// Ensure the prisma instance is re-used during hot-reloading
// Otherwise, a new client will be created on every reload
globalThis["prisma"] = globalThis["prisma"] || new PrismaClient()
prisma = globalThis["prisma"]
}
export default prisma
Right now with that code this plugin is worthless, because prisma doesn't get reinstantiated.
Proposal
On prisma schema change, in addition to clearing the require cache, also delete global.prisma
and globalThis.prisma
@flybayer I've slightly changed the code from above to manually disconnect the Prisma instance, everything is working good so far
export const prisma = createPrisma();
function createPrisma(): PrismaClient {
if (process.env.NODE_ENV === "production") {
return new PrismaClient({ log: ["warn", "error"] });
}
// Ensure that previous prisma instance is disconnected.
if ("prisma" in globalThis && "$disconnect" in globalThis["prisma"]) {
void globalThis["prisma"].$disconnect();
}
globalThis["prisma"] = new PrismaClient({
log: ["info", "query", "warn", "error"],
});
return globalThis["prisma"];
}