Singleton
A singleton is a type that has one instance. In JavaScript that is usually a module-level object, not a class with a private constructor.
Detailed Explanation
Some things are unique in a process: a logger config, a database pool, a feature-flag client. A singleton gives every importer the same object.
ES modules are singletons by default. The file evaluates once. export const db = createPool() is one pool. That is the pattern you should use. Classic textbooks write a class with getInstance() and a hidden instance variable; in JS that is extra machinery unless you need lazy init with a method.
let instance;
export function getClient() {
if (!instance) instance = connect();
return instance;
}
That is lazy singleton. Tests can reset instance if you export a _reset (ugly) or, better, inject the client and do not singleton it in testable code.
The browser has extra copies: each tab is a process-like heap. A singleton is per page, not per user. Shared workers and localStorage are how tabs coordinate. Node cluster and serverless have one singleton per process, so twelve workers are twelve pools.
What it costs you: hidden global state. Import order can matter if the singleton reads config at load. Tests leak (one test's db.fail = true poisons the next). Hot-reload in dev can evaluate the module twice and surprise you.
Reach for a module export when there really is one. Reach for a factory parameter when the object is a dependency. Never singleton a request-scoped object (the current user) on the server.
Hot module replacement in Vite and Next can re-evaluate a module and create a second pool next to the first. Guard with globalThis.__pool ??= createPool() in development if you see connection counts climb on every save. Do not use that trick to hide a real leak in production.
Configuration that changes per test (a different DATABASE_URL) cannot live in a singleton loaded at import time. Pass the config into createPool from the test.
Code Examples
config.js — evaluated once per process / page
// config.js — evaluated once per process / page
export const config = {
apiBase: process.env.API_BASE ?? "http://localhost:3000",
};let pool;
export function getPool() {
if (!pool) {
pool = { query: async () => [] };
}
return pool;
}
console.log(getPool() === getPool()); // => trueclass Store {
static #instance;
constructor() {
if (Store.#instance) return Store.#instance;
Store.#instance = this;
this.n = 0;
}
}
console.log(new Store() === new Store()); // => trueCommon Gotchas
Serverless and cluster multiply singletons
"one cache" is one cache per isolate. Use Redis if it must be shared.
Tests share the instance
reset state or inject mocks; do not rely on `import` creating a fresh copy.
A class singleton still needs a module boundary
two copies of the bundle can create two classes and two instances.
Lazy init must be safe under concurrency
JS is single-threaded, but `await connect()` without assigning `pool` first can start two connects. Assign a promise.