I am using Prisma and Next.js in development env, and I found multiple 'database connection initialized' printed when page hot-reloaded
import { PrismaClient } from "@prisma/client";
declare global {
var db: PrismaClient | undefined;
}
const create = () => {
console.log('database connection initialized');
return new PrismaClient()
}
const db = global.db || create();
if (process.env.NODE_ENV !== "production") global.db = db;
export {db}
This can lead to multiple instances of Prisma client being created, which consumes resources and might cause unexpected behavior.
How could I do this correctly?
Try to do something like this :
import { PrismaClient } from "@prisma/client";
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined;
};
export const db =
globalForPrisma.prisma ??
new PrismaClient({
// log: ['query'], // optionally log SQL queries in dev
});
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = db;
And I will try to explain as well as I can
globalThis
is used to store the client across hot reloads (just like you did with global
).
Only creates a new PrismaClient
if one doesn't exist.
Prevents re-logging database connection initialized
repeatedly.