Skip to content
jshacks.dev
Patterns

The Singleton Pattern in JavaScript, With Real Examples

The singleton pattern guarantees one instance of a class. See how ES modules already give you singletons, a class version, and the testing problems to avoid.

7 min read
Summarize in AI
Flat illustration of a service container binding interfaces to classes, with the JavaScript, npm and TypeScript logos.

The singleton pattern ensures a class has exactly one instance and provides a way to reach it. In Java or C++ that takes careful code: a private constructor, a static field and a static accessor. In JavaScript the language gives you singletons almost for free, because an ES module is evaluated once and its exports are shared by every importer. That makes the real question not "how do I write a singleton" but "should this be one at all", since a singleton is global state with a friendly name. This post shows the module-level singleton, the class version, a lazy version, the real uses (loggers, configuration, connection pools) and the testing and concurrency traps, on Node.js 24. Every sample prints its output.

The module is already a singleton

When a module is imported from several files, Node.js evaluates it once and caches the result. Every importer receives the same exports.

counter.mjsJavaScript
let count = 0;

export function increment() {
  count += 1;
  return count;
}

export function current() {
  return count;
}
a.mjsJavaScript
import { increment } from "./counter.mjs";
export const fromA = () => increment();
b.mjsJavaScript
import { increment, current } from "./counter.mjs";
import { fromA } from "./a.mjs";

fromA();
fromA();
increment();
console.log(current());
Text
3

Both a.mjs and b.mjs mutated the same count, since there is one copy of counter.mjs in the process. This is the simplest and most idiomatic JavaScript singleton: a module with private state and exported functions. No class, no getInstance.

The class version

Sometimes you want an object with methods and enforced uniqueness. Here is the classic shape.

config-singleton.mjsJavaScript
class Config {
  static #instance = null;
  #values;

  constructor(values) {
    if (Config.#instance) {
      throw new Error("Use Config.instance() instead of new Config()");
    }
    this.#values = values;
  }

  static instance() {
    Config.#instance ??= new Config({ region: "eu-west-1", debug: false });
    return Config.#instance;
  }

  get(key) {
    return this.#values[key];
  }
}

const a = Config.instance();
const b = Config.instance();
console.log(a === b, a.get("region"));

try {
  new Config({});
} catch (err) {
  console.log(err.message);
}
Text
true eu-west-1
Use Config.instance() instead of new Config()

instance() creates the object on first use and returns it afterward, which is lazy initialization. The static #instance private field cannot be reached from outside, and the constructor refuses a second creation once the first exists. JavaScript has no private constructors, so the guard has to live inside it. Compare the module version, which is a few lines shorter and just as unique.

Exporting an instance

A simpler variant avoids the accessor completely: build the object once and export it.

logger.mjsJavaScript
class Logger {
  #lines = [];

  log(message) {
    this.#lines.push(message);
    console.log(`[log] ${message}`);
  }

  get count() {
    return this.#lines.length;
  }
}

export const logger = new Logger();
use-logger.mjsJavaScript
import { logger } from "./logger.mjs";

logger.log("starting");
logger.log("ready");
console.log(logger.count);
Text
[log] starting
[log] ready
2

Every module that imports logger shares the same instance. If you do not export the Logger class, nobody can create a second one, which is the pattern without ceremony. This is how most Node.js libraries expose a default logger or client.

Real uses

A singleton fits when the thing is naturally unique in a process and expensive or confusing to duplicate.

  • A database connection pool. Many pools mean many sets of connections, and the database has a connection limit. One pool per process, shared by all code.

  • Configuration. Read the environment once at startup and expose the result.

  • A logger. One destination and format.

  • An in-memory cache. Duplicating it splits the hit rate.

pool.mjsJavaScript
class Pool {
  #open = 0;
  constructor(max) {
    this.max = max;
  }
  acquire() {
    if (this.#open >= this.max) throw new Error("Pool exhausted");
    this.#open += 1;
    return { release: () => (this.#open -= 1) };
  }
}

export const pool = new Pool(2);

const a = pool.acquire();
const b = pool.acquire();
try {
  pool.acquire();
} catch (err) {
  console.log(err.message);
}
a.release();
console.log(pool.acquire() !== undefined);
Text
Pool exhausted
true

If different modules created their own Pool(2), the limit would apply per module, not per process, and the database would see more connections than you planned.

The traps

Hidden dependencies and tests

A singleton is global state, and code that reaches for it has a dependency that its signature does not declare. The test problem follows directly: state from one test leaks into the next.

leak.mjsJavaScript
import assert from "node:assert/strict";
import { test } from "node:test";
import { increment, current } from "./counter.mjs";

test("first test increments", () => {
  increment();
  assert.equal(current(), 1);
});

test("second test sees leftover state", () => {
  assert.equal(current(), 1);
});
Text
✔ first test increments (0.7ms)
✔ second test sees leftover state (0.2ms)
ℹ tests 2
ℹ pass 2
ℹ fail 0

The second test passes only because the first ran before it. Run it alone, and it fails. Order-dependent tests are the classic singleton symptom. Fixes: add a reset() for tests, or better, do not import the singleton in business code, and pass it in as an argument from one composition root. That is dependency injection, and it keeps the single instance without the hidden coupling.

injected.mjsJavaScript
function makeOrderService({ logger }) {
  return { place: (id) => logger.log(`placed ${id}`) };
}

const calls = [];
const service = makeOrderService({ logger: { log: (m) => calls.push(m) } });
service.place("o-1");
console.log(calls);
Text
[ 'placed o-1' ]

Production wires the real logger once, and a test passes a fake. There is still one instance, but no code depends on a global.

Module identity can break

"Imported once" holds only when the module resolves to the same file. Three situations produce two copies.

  • Duplicate packages. If two dependencies pull different versions of a library into node_modules, each gets its own copy, and each has its own singleton.

  • Dual packages. A package that ships both CommonJS and ES module builds can load twice, once through require and once through import, giving two instances of its state.

  • Different URLs. Importing the same file by ./a.mjs and by ./a.mjs?v=2 creates two module instances, and a worker thread or a separate process always has its own.

worker-copy.mjsJavaScript
import { Worker, isMainThread, parentPort } from "node:worker_threads";
import { increment, current } from "./counter.mjs";

if (isMainThread) {
  increment();
  const worker = new Worker(new URL(import.meta.url));
  worker.on("message", (n) => {
    console.log(`main: ${current()}, worker: ${n}`);
    worker.terminate();
  });
} else {
  parentPort.postMessage(current());
}
Text
main: 1, worker: 0

The main thread incremented its copy to 1, and the worker, which loaded the module fresh, still sees 0. A singleton is per-realm, never per-application. In a cluster of processes, or across worker threads, shared state needs something external: a database, Redis or a SharedArrayBuffer.

Concurrency inside one process

JavaScript is single-threaded between await points, so a lazily created singleton cannot be created twice by two simultaneous callers, unless creation itself is asynchronous. An async initializer is the dangerous case.

async-init.mjsJavaScript
let client = null;
let creations = 0;

async function getClient() {
  if (!client) {
    creations += 1;
    await new Promise((resolve) => setTimeout(resolve, 10));
    client = { id: creations };
  }
  return client;
}

const [a, b] = await Promise.all([getClient(), getClient()]);
console.log(creations, a === b);
Text
2 false

Both callers saw client as null before either finished, so two clients were created. The fix is to cache the promise, not the result.

async-init-fixed.mjsJavaScript
let clientPromise = null;
let creations = 0;

function getClient() {
  clientPromise ??= (async () => {
    creations += 1;
    await new Promise((resolve) => setTimeout(resolve, 10));
    return { id: creations };
  })();
  return clientPromise;
}

const [a, b] = await Promise.all([getClient(), getClient()]);
console.log(creations, a === b);
Text
1 true

Now the second caller receives the same pending promise. If initialization can fail, clear clientPromise in a catch so a later call retries.

Alternatives

If you only need shared configuration, a frozen object export is enough. If you need one instance but want testability, create it in a composition root and inject it. If different parts of the system need different instances of the same thing, such as per-tenant caches, you want a factory or a registry keyed by tenant, not a singleton. Frameworks such as NestJS make every provider a singleton by default within the container's scope, which keeps the benefit and hides the hand-written boilerplate.

Where the advice stops

Do not ban singletons: a connection pool, a logger and parsed configuration are all well served by one shared instance. The pattern goes wrong when the singleton holds mutable business state and is imported from everywhere, so that any code can change it and any test can leak it. Keep the instance count at one, keep its state small and boring, and let the rest of your code receive it as an argument.

Singletons in frameworks you already use

Many tools you use daily are singleton-shaped. Node.js's process and console are one per process. A Next.js server module holds module-level state that lives for the lifetime of the server, which is why a database client created at the top of a file is reused across requests, and why, in development with hot reloading, people attach the client to globalThis so a reload does not open a new pool each time. That trick is a singleton that survives module re-evaluation, and it is a reminder that the guarantee is about module caching, and a tool that clears the cache breaks it.

Dependency-injection containers offer the same guarantee under another name. A "singleton scope" in NestJS or tsyringe means one instance per container, which is usually one per process. The difference from the hand-written version is where the instance is wired: the container creates it once and passes it to whoever asks, so your classes never import it directly. That is the form of the pattern with the least cost, because the lifetime is declared in one place and the consumers stay ordinary classes that take a parameter.

Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.