Singletons

suggest change

A singleton is an object that has exactly one instance in a program, available to every part of the program that needs it. Typical examples are a configuration object, a logger, a database connection pool, a cache or a registry of plugins.

In Java or C# you build a singleton with a private constructor and a static getInstance() method. In Node.js you usually don't need any of that: the module system already evaluates each module once and hands every importer the same exports. Most of the work is understanding when that guarantee holds and when it quietly breaks.

Need Node.js idiom
One shared object export it from a module
Expensive or configurable instance lazy getter with ??=
Async initialization cache the promise, not the result
Initialization before anything runs top-level await in the module
One instance across duplicate package copies globalThis[Symbol.for('...')]
Testable code export the class too, inject the instance

The examples were run with Node.js 24. Files ending in .mjs are ES modules, files ending in .cjs are CommonJS.

The module is the singleton

A module's top-level code runs the first time the module is imported. The result is cached, and every later import, including dynamic import(), gets the same module instance:

// counter.mjs
console.log('counter.mjs evaluated');

let count = 0;

export function increment() {
  return ++count;
}
// a.mjs
import { increment } from './counter.mjs';

export const incrementFromA = () => increment();
// main.mjs
import { increment } from './counter.mjs';
import { incrementFromA } from './a.mjs';
import * as m1 from './counter.mjs';
const m2 = await import('./counter.mjs');

console.log(increment(), incrementFromA(), increment());
console.log(m1 === m2);
counter.mjs evaluated
1 2 3
true

counter.mjs is imported four times but evaluated once, and count is shared by main.mjs and a.mjs. The variable count is not exported, so nobody can change it except through increment(). A module with private state and exported functions is the simplest singleton in Node.js.

CommonJS works the same way. module.exports is stored in require.cache, keyed by the resolved file name:

// logger.cjs
console.log('logger.cjs evaluated');

class Logger {
  #lines = [];

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

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

module.exports = new Logger();
// main.cjs
const path = require('node:path');
const logger1 = require('./logger.cjs');
const logger2 = require('./logger.cjs');
const logger3 = require(path.join(__dirname, 'logger.cjs'));

logger1.log('first');
logger2.log('second');
console.log(logger1 === logger2, logger1 === logger3, logger3.count);

const key = require.resolve('./logger.cjs');
console.log(path.basename(key), key in require.cache);

delete require.cache[key];
const logger4 = require('./logger.cjs');
console.log(logger4 === logger1, logger4.count);
logger.cjs evaluated
[1] first
[2] second
true true 2
logger.cjs true
logger.cjs evaluated
false 0

A relative path and an absolute path to the same file resolve to the same cache key, so they share the instance. Deleting the entry from require.cache makes the next require() evaluate the file again and create a second "singleton". Code that already holds logger1 keeps using the old one. See Invalidating the module cache.

Mixing module systems is fine as long as both refer to the same file. Importing a .cjs file from ESM uses require.cache, and since Node.js 22.12 require() of an ES module returns the same namespace object that import gets:

// mixed.mjs
import { createRequire } from 'node:module';
import loggerFromImport from './logger.cjs';
import * as counterNs from './counter.mjs';

const require = createRequire(import.meta.url);
const loggerFromRequire = require('./logger.cjs');
const counterFromRequire = require('./counter.mjs');

console.log(loggerFromImport === loggerFromRequire);
console.log(counterNs === counterFromRequire);
logger.cjs evaluated
counter.mjs evaluated
true
true

When the module cache gives you two instances

The cache key is the resolved file name (CommonJS) or URL (ESM). Anything that produces a different key produces a separate module instance with its own state.

Different URL for the same file

In ESM a query string or a hash is part of the URL:

// main2.mjs
const a = await import('./counter.mjs');
const b = await import('./counter.mjs?v=2');
const c = await import(new URL('./counter.mjs', import.meta.url).href);

console.log(a === b, a === c);
console.log(a.increment(), a.increment(), b.increment());
counter.mjs evaluated
counter.mjs evaluated
false true
1 2 1

That's sometimes used on purpose to reload a module, but each reload leaks the previous instance: ES modules can't be removed from the cache.

Different letter case

On case-insensitive file systems (Windows and macOS by default) ./LOGGER.cjs opens the same file as ./logger.cjs, but it's a different cache key:

// main4.cjs
const a = require('./logger.cjs');
const b = require('./LOGGER.cjs');
console.log(a === b);
logger.cjs evaluated
logger.cjs evaluated
false

On Linux the second require() fails with MODULE_NOT_FOUND, so the bug shows up only on some machines. Always use the exact file name.

Duplicate copies of a package

When two packages depend on incompatible versions of a library, npm installs two copies:

node_modules/
  registry/                  (1.0.0, used by the app)
  plugin/
    node_modules/
      registry/              (1.1.0, used by plugin)

Here registry keeps a map of handlers in module state:

// node_modules/registry/index.js (both copies)
const handlers = new Map();

export function register(name, fn) {
  handlers.set(name, fn);
}

export function names() {
  return [...handlers.keys()];
}
// node_modules/plugin/index.js
import { register } from 'registry';

register('plugin', () => 'hello from plugin');
// app.mjs
import 'plugin';
import { register, names } from 'registry';

register('app', () => 'hello from app');
console.log(names());
[ 'app' ]

The plugin registered itself in its own copy of registry, which the app never sees. The same thing breaks instanceof checks: an object created by one copy's class is not an instance of the other copy's class.

Run npm ls registry to find duplicates and npm dedupe (or aligning version ranges) to remove them.

Dual CommonJS / ESM packages

A package that ships separate files for import and require creates the same problem inside a single version:

{
  "name": "store",
  "exports": {
    "import": "./index.mjs",
    "require": "./index.cjs"
  }
}
// node_modules/store/index.mjs
export const items = [];
// node_modules/store/index.cjs
exports.items = [];
// app.mjs
import { createRequire } from 'node:module';
import { items } from 'store';

const require = createRequire(import.meta.url);
const cjs = require('store');

items.push('added via import');
console.log(items === cjs.items, cjs.items.length);
false 0

This is called the dual package hazard. If you publish a package with state, ship one implementation and have the other entry point re-export it, or keep the state outside the module as shown next.

A process-wide singleton with globalThis

globalThis is shared by every module in a thread, no matter which copy or format it came from. Symbol.for(key) returns the same symbol for the same string everywhere, which makes it a good collision-free property name:

// node_modules/registry/index.js (both copies)
const KEY = Symbol.for('registry.handlers');
globalThis[KEY] ??= new Map();
const handlers = globalThis[KEY];

export function register(name, fn) {
  handlers.set(name, fn);
}

export function names() {
  return [...handlers.keys()];
}

Running the same app.mjs now prints:

[ 'plugin', 'app' ]

The first copy to load creates the map, and every other copy reuses it. Use a key that includes the package name to avoid clashing with other libraries. If the shared object's shape can change between versions, put a version number in the key or check it at runtime.

The same trick keeps one database client alive when a development server re-evaluates your modules on every change (frameworks with hot reloading do this). Without it every reload opens a new connection pool:

// db.mjs
import pg from 'pg';

const KEY = Symbol.for('myapp.pgPool');

export const pool = (globalThis[KEY] ??= new pg.Pool({
  connectionString: process.env.DATABASE_URL,
}));

Use this only when you need it. A global is harder to find, test and reset than a module export.

Lazy creation

Exporting an instance creates it as soon as anything imports the module, even if it's never used, and before the program had a chance to read its configuration. A getter delays creation until the first call:

// settings.mjs
class Settings {
  constructor(file) {
    console.log(`loading ${file}`);
    this.file = file;
  }
}

let instance = null;

export function getSettings() {
  instance ??= new Settings(process.env.SETTINGS_FILE ?? 'settings.json');
  return instance;
}

??= assigns only when instance is null or undefined, so the constructor runs once. JavaScript code runs on a single thread, so two synchronous calls can't race here.

Async initialization: cache the promise

Most real singletons need async setup: connecting to a database, reading a file, fetching credentials. The obvious version is wrong:

// async-bad.mjs
import { setTimeout as sleep } from 'node:timers/promises';

let connects = 0;
async function connect() {
  const id = ++connects;
  await sleep(50);
  return { id };
}

let client = null;

async function getClient() {
  if (client === null) {
    client = await connect();
  }
  return client;
}

const [a, b, c] = await Promise.all([getClient(), getClient(), getClient()]);
console.log(a.id, b.id, c.id, 'connects:', connects);
1 2 3 connects: 3

All three calls check client before the first await connect() finishes, so each one connects. In a web server this happens when the first few requests arrive at the same time after startup. See Race conditions for more of this kind of bug.

The fix is to store the promise synchronously, before any await. Every caller then awaits the same pending promise. Also clear it on failure, otherwise one failed connection attempt is cached forever:

// async-good.mjs
import { setTimeout as sleep } from 'node:timers/promises';

let attempts = 0;
async function connect() {
  attempts++;
  await sleep(50);
  if (attempts === 1) throw new Error('ECONNREFUSED');
  return { id: attempts };
}

let clientPromise = null;

function getClient() {
  clientPromise ??= connect().catch((err) => {
    clientPromise = null; // allow a retry on the next call
    throw err;
  });
  return clientPromise;
}

const results = await Promise.allSettled([getClient(), getClient()]);
console.log(results.map((r) => r.status + ' ' + (r.reason?.message ?? r.value.id)));

const [a, b] = await Promise.all([getClient(), getClient()]);
console.log(a.id, b.id, a === b, 'attempts:', attempts);
[ 'rejected ECONNREFUSED', 'rejected ECONNREFUSED' ]
2 2 true attempts: 2

The two concurrent calls shared the first, failed attempt. The next calls started a fresh attempt and shared its result.

Initialization with top-level await

In ES modules you can await at the top level. The importing modules don't run until the awaited module finishes, so they can use the instance directly without a getter:

// db.mjs
import { setTimeout as sleep } from 'node:timers/promises';

console.log('db.mjs: connecting...');
await sleep(100); // stands in for a real connect()
console.log('db.mjs: connected');

export const db = {
  query: (sql) => `result of ${sql}`,
};
// users.mjs
import { db } from './db.mjs';

console.log('users.mjs evaluated');
export const listUsers = () => db.query('SELECT * FROM users');
// main.mjs
import { db } from './db.mjs';
import { listUsers } from './users.mjs';

console.log('main.mjs evaluated');
console.log(listUsers());
db.mjs: connecting...
db.mjs: connected
users.mjs evaluated
main.mjs evaluated
result of SELECT * FROM users

The trade-offs: startup is blocked until the connection succeeds, a failure crashes the import with no chance to retry, and a module with top-level await can't be loaded with require(). It works well for application entry-point code and poorly for libraries.

Class-based singletons

If you prefer a class, the module export still does the job: export const logger = new Logger(). When you need to stop others from creating extra instances, a static private field can hold the instance, and another private flag can make the constructor refuse direct calls (JavaScript has no private constructors):

// cls.mjs
class Settings {
  static #instance = null;
  static #constructing = false;

  #values = new Map();

  constructor() {
    if (!Settings.#constructing) {
      throw new TypeError('use Settings.getInstance()');
    }
  }

  static getInstance() {
    if (Settings.#instance === null) {
      Settings.#constructing = true;
      try {
        Settings.#instance = new Settings();
      } finally {
        Settings.#constructing = false;
      }
    }
    return Settings.#instance;
  }

  get(key) { return this.#values.get(key); }
  set(key, value) { this.#values.set(key, value); }
}

Settings.getInstance().set('theme', 'dark');
console.log(Settings.getInstance().get('theme'));
console.log(Settings.getInstance() === Settings.getInstance());

try {
  new Settings();
} catch (err) {
  console.log(err.message);
}
dark
true
use Settings.getInstance()

This is more code than a module export and gives no extra protection against the duplicate-module problems above: each copy of the class has its own #instance. Use it when porting code or when the API must look like that.

Read-only singletons

A shared configuration object is easy to modify by accident from anywhere in the program. Object.freeze() makes such writes throw in strict mode (ES modules and classes are always strict). It's shallow, so freeze nested objects too:

// frozen.mjs
const config = Object.freeze({
  port: Number(process.env.PORT ?? 3000),
  db: Object.freeze({ host: 'localhost', pool: 10 }),
});

try {
  config.port = 80;
} catch (err) {
  console.log(err.constructor.name + ':', err.message);
}
console.log(config.port, Object.isFrozen(config.db));
TypeError: Cannot assign to read only property 'port' of object '#<Object>'
3000 true

One instance per thread, not per machine

A module singleton lives in one JavaScript realm. Each worker thread loads its own copy of every module:

// workers.mjs
import { Worker, isMainThread, threadId } from 'node:worker_threads';
import { increment } from './counter.mjs';

increment();
increment();
console.log(`thread ${threadId}: count is now ${increment()}`);

if (isMainThread) {
  new Worker(new URL(import.meta.url));
}
counter.mjs evaluated
thread 0: count is now 3
counter.mjs evaluated
thread 1: count is now 3

The same holds for processes started with the cluster module, child_process.fork(), or several replicas of your server behind a load balancer. An in-memory cache, rate limiter or counter is per process. If the state must be shared, keep it in Redis, a database, or pass messages to one owner thread.

Singletons and testing

Module-level state survives between tests in the same file, and tests that depend on each other's leftovers are fragile. A simple rule avoids most problems: export the class (or a factory) as well as the shared instance.

// cache.mjs
export class Cache {
  #map = new Map();
  #maxSize;

  constructor({ maxSize = 1000 } = {}) {
    this.#maxSize = maxSize;
  }

  get(key) { return this.#map.get(key); }

  set(key, value) {
    if (this.#map.size >= this.#maxSize) {
      // evict the oldest entry (Map keeps insertion order)
      this.#map.delete(this.#map.keys().next().value);
    }
    this.#map.set(key, value);
  }

  get size() { return this.#map.size; }
}

// the shared instance used by application code
export const cache = new Cache();

Tests create a fresh instance each time and never touch the shared one:

// cache.test.mjs
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { Cache } from './cache.mjs';

test('stores values', () => {
  const cache = new Cache();
  cache.set('a', 1);
  assert.equal(cache.get('a'), 1);
  assert.equal(cache.size, 1);
});

test('evicts the oldest entry', () => {
  const cache = new Cache({ maxSize: 2 });
  cache.set('a', 1);
  cache.set('b', 2);
  cache.set('c', 3);
  assert.equal(cache.get('a'), undefined);
  assert.equal(cache.size, 2);
});
$ node --test
✔ stores values (0.9287ms)
✔ evicts the oldest entry (0.2201ms)
ℹ tests 2
ℹ pass 2
ℹ fail 0

Code that uses the singleton is harder to test when it imports the instance directly. Passing the instance in instead (dependency injection) keeps the "only one" decision in a single place, the entry point, and lets tests pass a fake (see Mocks and test doubles):

// di.mjs
class UserService {
  #cache;

  constructor({ cache }) {
    this.#cache = cache;
  }

  async getUser(id) {
    let user = this.#cache.get(id);
    if (user === undefined) {
      user = { id, name: `user${id}` };
      this.#cache.set(id, user);
    }
    return user;
  }
}

// entry point: create one cache and share it explicitly
const cache = new Map();
const users = new UserService({ cache });
const admin = new UserService({ cache });

const u1 = await users.getUser(7);
const u2 = await admin.getUser(7);
console.log(u1 === u2, cache.size);
true 1

Summary

See also Design patterns and How modules are loaded.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents