Design patterns
suggest changeClassic design patterns (Singleton, Factory, Observer, Decorator...) were described for languages like C++ and Java. In Node.js many of them look different, or disappear entirely, because JavaScript has first-class functions, closures, and a module system that caches modules.
This article shows the patterns you will actually meet in Node.js code and in its standard library, written in modern JavaScript (ES modules, async / await, private class fields). The examples run as-is with Node.js 22 or later; save them as .mjs files.
| Pattern | Node.js idiom |
|---|---|
| Singleton | an exported module value (modules are cached) |
| Factory | a function returning an object |
| Encapsulation | closures or #private fields |
| Dependency injection | pass dependencies to a constructor or factory |
| Observer | EventEmitter |
| Chain of responsibility | middleware ((ctx, next) => ...) |
| Decorator | higher-order functions, Proxy |
| Adapter | util.promisify(), util.callbackify() |
| Strategy | an object map of functions |
| Iterator | async generators, for await |
| Pipes and filters | stream.pipeline() |
Singleton: the module is the instance
A module is evaluated once, the first time it is imported. Every later import (or require) gets the same cached module instance. That means any value exported from a module is effectively a singleton:
// config.mjs
console.log('config.mjs evaluated');
let counter = 0;
export const config = {
port: Number(process.env.PORT ?? 3000),
env: process.env.NODE_ENV ?? 'development',
};
export function nextId() {
return ++counter;
}
// a.mjs
import { nextId } from './config.mjs';
export const fromA = () => nextId();
// singleton.mjs
import { config, nextId } from './config.mjs';
import { fromA } from './a.mjs';
console.log(config.port, config.env);
console.log(nextId(), fromA(), nextId());
config.mjs evaluated
3000 development
1 2 3
config.mjs is imported twice (by singleton.mjs and by a.mjs) but evaluated only once, and both importers share the same counter.
Two caveats:
- The cache is keyed by the resolved file path (URL). If two copies of a package end up in different
node_modulesdirectories, you get two "singletons". The same happens with dual packages when one part of your apprequire()s the CommonJS build and anotherimports the ESM build. - Module-level state is shared by everything in the process, which makes testing harder. Prefer exporting a factory and creating one instance in your app's entry point (see dependency injection below).
If creating the instance is expensive or depends on runtime configuration, create it lazily:
class Database {
constructor(url) {
console.log(`connecting to ${url}`);
this.url = url;
}
}
let instance;
export function getDb() {
instance ??= new Database(process.env.DB_URL ?? 'postgres://localhost/app');
return instance;
}
console.log(getDb() === getDb());
connecting to postgres://localhost/app
true
The ??= operator assigns only when instance is null or undefined, so the constructor runs once. See How modules are loaded for details of module resolution and caching.
Factory
A factory is a function that creates objects. It hides which concrete class is used, so callers depend only on the interface (here: "has a log() method"):
class ConsoleLogger {
log(msg) { console.log(`[console] ${msg}`); }
}
class JsonLogger {
log(msg) { console.log(JSON.stringify({ time: '2026-10-17T10:00:00Z', msg })); }
}
class NullLogger {
log() {}
}
const loggers = {
console: ConsoleLogger,
json: JsonLogger,
silent: NullLogger,
};
export function createLogger(kind = 'console') {
const Logger = loggers[kind];
if (!Logger) throw new Error(`unknown logger: ${kind}`);
return new Logger();
}
createLogger().log('server started');
createLogger('json').log('server started');
createLogger('silent').log('server started');
try {
createLogger('xml');
} catch (err) {
console.log(err.message);
}
[console] server started
{"time":"2026-10-17T10:00:00Z","msg":"server started"}
unknown logger: xml
The silent logger is a Null Object: it has the right shape but does nothing, so callers never have to write if (logger) logger.log(...).
Factories are all over the standard library: http.createServer(), fs.createReadStream(), crypto.createHash(), net.connect(). They let Node.js change the class behind the API without breaking your code.
Encapsulation: closures and private fields
A factory function can keep state in a closure. Only the functions it returns can reach that state. Classes can do the same with #private fields:
function createCounter(start = 0) {
let value = start;
return {
increment() { return ++value; },
reset() { value = start; },
get value() { return value; },
};
}
const c = createCounter(10);
c.increment();
c.increment();
console.log(c.value);
try { c.value = 100; } catch (err) { console.log(err.constructor.name); }
console.log(c.value);
console.log(Object.keys(c));
class Account {
#balance = 0;
deposit(amount) {
if (amount <= 0) throw new RangeError('amount must be positive');
this.#balance += amount;
return this;
}
get balance() { return this.#balance; }
}
const acc = new Account().deposit(50).deposit(25);
console.log(acc.balance, Object.keys(acc));
12
TypeError
12
[ 'increment', 'reset', 'value' ]
75 []
value is a getter without a setter, so assigning to it throws a TypeError (ES modules always run in strict mode; in sloppy mode the assignment would silently do nothing). #balance doesn't show up in Object.keys(), JSON.stringify() or for...in, and writing acc.#balance outside the class is a syntax error.
Returning this from deposit() enables method chaining, the fluent style you know from Express's res.status(404).json(...) and from query builders.
Dependency injection
Instead of importing its collaborators directly, a class receives them as arguments. In production you pass the real database and mailer; in tests you pass fakes:
export class UserService {
#db;
#mailer;
constructor({ db, mailer }) {
this.#db = db;
this.#mailer = mailer;
}
async register(email) {
const user = await this.#db.insert('users', { email });
await this.#mailer.send(email, 'Welcome!');
return user;
}
}
// test doubles
const fakeDb = {
rows: [],
async insert(table, row) {
const saved = { id: this.rows.length + 1, ...row };
this.rows.push(saved);
return saved;
},
};
const sent = [];
const fakeMailer = {
async send(to, subject) { sent.push({ to, subject }); },
};
const service = new UserService({ db: fakeDb, mailer: fakeMailer });
console.log(await service.register('ann@example.com'));
console.log(sent);
{ id: 1, email: 'ann@example.com' }
[ { to: 'ann@example.com', subject: 'Welcome!' } ]
Passing a single object ({ db, mailer }) instead of positional arguments makes the order irrelevant and lets you add dependencies later without breaking callers. The app's entry point (the composition root) is then the only place that knows which concrete implementations are used:
// main.mjs
const db = await createPostgres(process.env.DATABASE_URL);
const mailer = createSmtpMailer({ host: 'smtp.example.com' });
const users = new UserService({ db, mailer });
Most Node.js projects don't need a DI container library; plain constructor arguments go a long way. See Dependency Injection for more.
Observer: EventEmitter
The Observer pattern lets objects subscribe to events from a subject without the subject knowing who listens. In Node.js this is EventEmitter, the base class of streams, HTTP servers, sockets, child processes and process itself:
import { EventEmitter, once } from 'node:events';
class OrderQueue extends EventEmitter {
#orders = [];
add(order) {
this.#orders.push(order);
this.emit('added', order);
if (this.#orders.length >= 2) {
this.emit('full', this.#orders.length);
}
}
}
const queue = new OrderQueue();
queue.on('added', (order) => console.log('audit log:', order.id));
queue.on('added', (order) => console.log('send email for', order.id));
queue.once('full', (n) => console.log(`queue has ${n} orders`));
queue.add({ id: 'A1' });
queue.add({ id: 'A2' });
queue.add({ id: 'A3' });
setTimeout(() => queue.add({ id: 'B1' }), 10);
const [order] = await once(queue, 'added');
console.log('awaited', order.id);
audit log: A1
send email for A1
audit log: A2
send email for A2
queue has 2 orders
audit log: A3
send email for A3
audit log: B1
send email for B1
awaited B1
Things to know about EventEmitter:
emit()calls listeners synchronously, in registration order. A slow listener blocks the emitter.- The
once()method removes the listener after the first call, which is why "queue has ... orders" is printed only once. - The
events.once(emitter, name)function returns a promise, so you canawaita single event. - Emitting
'error'with no'error'listener throws. Always listen for'error'on emitters that can fail. - Node.js warns when more than 10 listeners are added for one event on one emitter. That usually means a leak: listeners added per request and never removed with
off().
More in Event Emitters.
Chain of responsibility: middleware
Express, Koa, Fastify hooks and many other libraries process a request with a chain of middleware functions. Each one can act on the request, pass control to the next one by calling next(), or stop the chain. Here's a tiny Koa-style implementation:
function compose(middlewares) {
return function run(ctx) {
function dispatch(i) {
const fn = middlewares[i];
if (!fn) return Promise.resolve();
return Promise.resolve(fn(ctx, () => dispatch(i + 1)));
}
return dispatch(0);
};
}
const logger = async (ctx, next) => {
ctx.log.push(`--> ${ctx.path}`);
await next();
ctx.log.push(`<-- ${ctx.path} ${ctx.status}`);
};
const auth = async (ctx, next) => {
if (!ctx.user) {
ctx.status = 401;
return; // stop the chain
}
await next();
};
const handler = async (ctx) => {
ctx.status = 200;
ctx.body = `hello ${ctx.user}`;
};
const app = compose([logger, auth, handler]);
for (const user of ['ann', undefined]) {
const ctx = { path: '/me', user, log: [] };
await app(ctx);
console.log(ctx.status, ctx.body, ctx.log);
}
200 hello ann [ '--> /me', '<-- /me 200' ]
401 undefined [ '--> /me', '<-- /me 401' ]
Because next() returns a promise, code after await next() runs on the way back out, after all later middleware has finished. That's how logger sees the final status. auth stops the chain for anonymous users simply by not calling next().
For Express-specific middleware see Custom middleware in Express.
Decorator: wrapping functions
A decorator adds behavior to an object or function without changing it. With first-class functions, the simplest decorator is a function that takes a function and returns a new one with the same signature:
function withRetry(fn, { retries = 3, delayMs = 10 } = {}) {
return async function (...args) {
for (let attempt = 1; ; attempt++) {
try {
return await fn.apply(this, args);
} catch (err) {
if (attempt > retries) throw err;
console.log(`attempt ${attempt} failed: ${err.message}, retrying`);
await new Promise((r) => setTimeout(r, delayMs * attempt));
}
}
};
}
function memoize(fn) {
const cache = new Map();
return function (key) {
if (!cache.has(key)) cache.set(key, fn.call(this, key));
return cache.get(key);
};
}
let calls = 0;
async function flakyFetch(url) {
calls++;
if (calls < 3) throw new Error('ECONNRESET');
return `contents of ${url}`;
}
const fetchWithRetry = withRetry(flakyFetch);
console.log(await fetchWithRetry('https://example.com'));
const slowSquare = (n) => { console.log(`computing ${n}`); return n * n; };
const fastSquare = memoize(slowSquare);
console.log(fastSquare(9), fastSquare(9), fastSquare(4));
attempt 1 failed: ECONNRESET, retrying
attempt 2 failed: ECONNRESET, retrying
contents of https://example.com
computing 9
computing 4
81 81 16
The wrapper is a regular function (not an arrow function) and calls fn.apply(this, args), so this still works when the decorated function is used as a method. Decorators compose: withRetry(withTimeout(fetchUser)).
The @decorator syntax for classes is a TC39 proposal that Node.js doesn't support yet; you need TypeScript or Babel for it.
Decorating whole objects with Proxy
To wrap every method of an object, use a Proxy. This one logs every method call on a Map:
function traced(target, name) {
return new Proxy(target, {
get(obj, prop) {
const value = Reflect.get(obj, prop);
if (typeof value !== 'function') return value;
return function (...args) {
console.log(`${name}.${String(prop)}(${args.map((a) => JSON.stringify(a)).join(', ')})`);
return value.apply(obj, args);
};
},
});
}
const cache = traced(new Map(), 'cache');
cache.set('user:1', { name: 'Ann' });
console.log(cache.get('user:1'));
console.log(cache.size);
cache.set("user:1", {"name":"Ann"})
cache.get("user:1")
{ name: 'Ann' }
1
Note Reflect.get(obj, prop) and value.apply(obj, args): built-in objects like Map, Set and Date keep their data in internal slots, so their methods and getters must run on the real object, not on the proxy. Passing the proxy as the receiver (Reflect.get(obj, prop, receiver)) makes cache.size throw TypeError: Method get Map.prototype.size called on incompatible receiver.
Adapter: callbacks to promises and back
An adapter converts one interface into another. The most common case in Node.js is turning an old error-first callback API into a promise-based one. util.promisify() does it for you, and util.callbackify() goes the other way:
import { promisify, callbackify } from 'node:util';
// legacy API using error-first callbacks
function legacyLookup(name, cb) {
setTimeout(() => {
if (name === 'missing') cb(new Error('not found'));
else cb(null, { name, ip: '10.0.0.7' });
}, 5);
}
const lookup = promisify(legacyLookup);
console.log(await lookup('db'));
try {
await lookup('missing');
} catch (err) {
console.log('error:', err.message);
}
// the other direction: expose an async function to callback-style callers
async function modernStat(path) {
return { path, size: 1024 };
}
callbackify(modernStat)('/tmp/x', (err, info) => console.log(err, info));
{ name: 'db', ip: '10.0.0.7' }
error: not found
null { path: '/tmp/x', size: 1024 }
Most core modules already ship promise versions (node:fs/promises, node:dns/promises, node:stream/promises, node:timers/promises), so use those directly. See Callback to Promise.
Strategy: a map of functions
The Strategy pattern selects an algorithm at runtime. In JavaScript you don't need a Strategy interface with one class per algorithm; an object whose values are functions is enough. Here the strategy is a compression algorithm chosen from the Accept-Encoding header:
import { gzipSync, brotliCompressSync, deflateSync } from 'node:zlib';
const encoders = {
br: (buf) => brotliCompressSync(buf),
gzip: (buf) => gzipSync(buf),
deflate: (buf) => deflateSync(buf),
identity: (buf) => buf,
};
function pickEncoding(acceptEncoding = '') {
const accepted = acceptEncoding.split(',').map((s) => s.trim().split(';')[0]);
return ['br', 'gzip', 'deflate'].find((e) => accepted.includes(e)) ?? 'identity';
}
const body = Buffer.from('hello world '.repeat(200));
for (const header of ['gzip, deflate, br', 'gzip', '']) {
const enc = pickEncoding(header);
const out = encoders[enc](body);
console.log(`${JSON.stringify(header).padEnd(20)} -> ${enc.padEnd(8)} ${out.length} bytes`);
}
"gzip, deflate, br" -> br 26 bytes
"gzip" -> gzip 52 bytes
"" -> identity 2400 bytes
Adding a new algorithm means adding one entry to encoders, with no switch statement to update. (A real server would also honor q= weights and use the streaming zlib APIs.)
Iterator: async generators
Async generators are the idiomatic way to expose a sequence of values that arrive over time: pages from a paginated API, rows from a database cursor, lines from a file. The consumer uses for await and doesn't need to know about pages at all:
async function* paginate(fetchPage) {
let page = 1;
while (true) {
const { items, hasMore } = await fetchPage(page);
yield* items;
if (!hasMore) return;
page++;
}
}
// fake API: 3 pages of 2 items
async function fetchPage(page) {
console.log(`fetching page ${page}`);
return { items: [`item${page}a`, `item${page}b`], hasMore: page < 3 };
}
for await (const item of paginate(fetchPage)) {
console.log(item);
if (item === 'item2b') break;
}
fetching page 1
item1a
item1b
fetching page 2
item2a
item2b
The generator is lazy: page 3 is never fetched because the loop stopped. break also runs any finally block in the generator, which is where you'd close a cursor or connection. Readable streams, readline interfaces and events.on() are async iterable too.
Pipes and filters: stream pipelines
Streams let you build processing pipelines out of small, independent stages. stream.pipeline() connects them, propagates errors, and destroys every stage when one fails. Stages can be streams or async generator functions:
import { pipeline } from 'node:stream/promises';
import { Readable, Writable } from 'node:stream';
const source = Readable.from(['3', '1', 'x', '4', '1', '5']);
async function* parseNumbers(lines) {
for await (const line of lines) {
const n = Number(line);
if (!Number.isNaN(n)) yield n;
}
}
async function* square(nums) {
for await (const n of nums) yield n * n;
}
const sink = new Writable({
objectMode: true,
write(n, _enc, done) {
console.log('got', n);
done();
},
});
await pipeline(source, parseNumbers, square, sink);
console.log('pipeline finished');
got 9
got 1
got 16
got 1
got 25
pipeline finished
Each stage only knows about its input and output, so you can reorder, reuse and test stages separately. Backpressure is handled for you: a slow sink automatically slows down the source. See Using Streams.
Summary
- Don't port Java-style patterns literally. In Node.js many patterns collapse into a function, a closure or a module.
- A module's exports are singletons, but prefer creating shared instances in the entry point and injecting them.
- Use factories to hide concrete classes, and closures or
#privatefields to hide state. - Pass dependencies in (
new Service({ db, mailer })) to make code testable. EventEmitteris the built-in Observer; always handle'error'.- Middleware is a chain of responsibility; higher-order functions and
Proxyare decorators. - Use
util.promisify()to adapt callback APIs, object maps of functions for strategies, async generators for iterators andstream.pipeline()for processing pipelines.