From 8bd5e33b26f84da8445f86c3d6d169de9cc8e892 Mon Sep 17 00:00:00 2001 From: Jack Griffiths Date: Wed, 30 Dec 2020 18:33:40 +0000 Subject: [PATCH] Hot reload fix for development environments Next.js hot reloading on a development environment creates a new instance of Prisma (and any other database client). See https://github.com/vercel/next.js/issues/7811. This checks the environment of the Next.js app, and spins-up a Prisma instance accordingly. --- lib/prisma.ts | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/lib/prisma.ts b/lib/prisma.ts index a85a361..66e280c 100644 --- a/lib/prisma.ts +++ b/lib/prisma.ts @@ -1,4 +1,18 @@ import { PrismaClient } from "@prisma/client"; -const prisma = new PrismaClient(); -export default prisma; \ No newline at end of file +let prisma + +if ( process.env.NODE_ENV === "production" ) { + // spin-up a Prisma client always on the production copy. + prisma = new PrismaClient() + +} else { + // to prevent Prisma spinning-up too many clients in a development environment, check to see if one is already running + if (!global.prisma) { + global.prisma = new PrismaClient() + } + + prisma = global.prisma +} + +export default prisma