javascript / intermediate
Snippet
The Singleton Pattern for Database Connections
In development, Next.js frequently reloads modules. Without the Singleton pattern, every hot-reload would create a new database connection, eventually exhausting the pool. This pattern stores the instance globally.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
import { PrismaClient } from '@prisma/client';const prismaClientSingleton = () => new PrismaClient();const globalForPrisma = globalThis as unknown as {prisma: PrismaClient | undefined;};const prisma = globalForPrisma.prisma ??= prismaClientSingleton();export default prisma;if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma;
nextjs
Breakdown
1
globalThis
A standard way to access the global scope across different environments (Node.js/Browser).
2
??=
The logical nullish assignment operator, which only assigns if the variable is null or undefined.