javascript / expert
Snippet
Isomorphic Singleton Pattern for Data Sources
In Next.js development mode, Hot Module Replacement (HMR) can cause multiple instances of database connections. Attaching the instance to 'globalThis' ensures a singleton pattern that persists across reloads, preventing connection exhaustion.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
const globalForDatabase = globalThis;export const db = globalForDatabase.db ?? (() => {const instance = new DatabaseConnection();if (process.env.NODE_ENV !== 'production') {globalForDatabase.db = instance;}return instance;})();// Usage in Next.js Server Componentsimport { db } from './db';
nextjs
Breakdown
1
const globalForDatabase = globalThis;
References the global execution context, which persists during HMR in Node.js.
2
globalForDatabase.db ?? (() => { ... })();
Uses the Nullish Coalescing operator to either retrieve the existing instance or initialize a new one.
3
if (process.env.NODE_ENV !== 'production')
Ensures the global pollution only occurs in development to aid HMR stability.