Skip to content
jshacks.dev
Patterns

Implement a singleton with an ES module

Implement a singleton with an ES module in JavaScript: a module runs once, so its exports are one shared instance. Node.js 24.

1 min read
Summarize in AI

You do not need a class with a static getInstance to get one shared object. A module is evaluated once, and everything that imports it gets the same exports.

logger.mjsJavaScript
console.log('logger created');

export const logger = {
  lines: [],
  log(message) {
    this.lines.push(message);
  },
};
main.mjsJavaScript
const first = await import('./logger.mjs');
const second = await import('./logger.mjs');

console.log(first.logger === second.logger);
Text
logger created
true

The console.log at the top of logger.mjs runs once, on the first import, and the second import reuses the cached module. Both namespaces point at the same logger object, so state set through one is visible through the other. The behaviour is part of how modules are loaded in Node.js.

The cache is keyed by the full URL. ./logger.mjs?v=2 is a different module and runs again, and so is a copy of the file reached by another path, such as when two versions of a package are installed. Tests that need a fresh instance can use that on purpose.

Taggednode 24
Share

More snippets

Get new posts by email

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

Unsubscribe in one click. No spam, ever.