Skip to content

Commit e277287

Browse files
🎨 refactor: update Prisma singleton pattern to avoid issues with hot reloading
Update the Prisma singleton pattern to use a factory function instead of directly referencing the global object. This change prevents potential issues with hot reloading in development environments by ensuring a new Prisma client instance is created when necessary. The updated code also leverages the globalThis object and conditionally assigns the Prisma client instance to avoid recreating it in production.
1 parent 35e8352 commit e277287

1 file changed

Lines changed: 9 additions & 5 deletions

File tree

‎apps/web/app/utils.ts‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,16 @@ type OpenGraphType = "article" | "website" | "book" | "profile" | "music.song" |
88

99

1010
// Singleton pattern for Prisma Client
11-
let prisma: PrismaClient;
12-
if (!global.prisma) {
13-
global.prisma = new PrismaClient();
11+
const prismaClientSingleton = () => {
12+
return new PrismaClient()
1413
}
15-
prisma = global.prisma;
16-
export { prisma };
14+
declare global {
15+
var prismaGlobal: undefined | ReturnType<typeof prismaClientSingleton>
16+
}
17+
const prisma = globalThis.prismaGlobal ?? prismaClientSingleton()
18+
export { prisma }
19+
if (process.env.NODE_ENV !== 'production') globalThis.prismaGlobal = prisma
20+
1721

1822
import LoopsClient from "loops";
1923
import { ZodError, ZodIssue } from "zod";

0 commit comments

Comments
 (0)