What is the Singleton Pattern?

The Singleton pattern ensures a class or module has exactly one instance and provides a single shared access point to it, for example one database connection pool, configuration object, logger or app-wide store.

In JavaScript, modules are already singletons

An ES module is evaluated once, and every import receives the same exports. So exporting an instance (export const logger = new Logger()) is the simplest and most idiomatic singleton, with no special class code needed.

Class-based singleton

Store the instance in a static (ideally private) field and return it from the constructor or a getInstance() method. Useful when the instance must be created lazily or configured on first use.

Real-world places you see it

  • Database clients (e.g. one Prisma client, reused across hot reloads in Next.js dev by storing it on globalThis).
  • Analytics, logging and feature-flag clients.
  • Global state stores.

Criticisms

  • Hidden global state: any code can reach and change it, making dependencies implicit.
  • Testing: state leaks between tests; you need reset hooks or dependency injection.
  • Server-side rendering: a module singleton is shared by all requests on the server. Storing per-user data in it leaks data between users. Keep request-specific data in request scope.

Alternative

Create the instance once at the composition root and pass it to whoever needs it (dependency injection). That keeps "only one" without hidden coupling.

Code example

js
1// 1. Idiomatic: a module-level instance (every import gets the same object)
2class Logger {
3 #lines = [];
4 log(msg) {
5 this.#lines.push(`${new Date(0).toISOString().slice(11, 19)} ${msg}`);
6 }
7 get count() {
8 return this.#lines.length;
9 }
10}
11const logger = new Logger(); // export const logger = new Logger();
12
13// 2. Class-based singleton with lazy creation
14class Config {
15 static #instance = null;
16 constructor() {
17 if (Config.#instance) return Config.#instance;
18 this.values = { apiUrl: "https://api.example.com", retries: 3 };
19 Config.#instance = this;
20 }
21 static getInstance() {
22 return Config.#instance ?? new Config();
23 }
24}
25
26const a = new Config();
27const b = Config.getInstance();
28const c = new Config();
29console.log(a === b, b === c); // true true
30b.values.retries = 5;
31console.log(a.values.retries); // 5 - same instance everywhere
32
33logger.log("app started");
34logger.log("user logged in");
35console.log(logger.count); // 2
36
37// 3. The Next.js dev pattern: survive hot reloads by caching on globalThis
38const globalForDb = globalThis;
39globalForDb.__db ??= { createdAt: "once", query: (sql) => `result of ${sql}` };
40const db = globalForDb.__db;
41console.log(db.query("select 1")); // result of select 1

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app