Full answer
Good plugin design starts from what users need to change, and from what you must keep stable.
Design choices:
- Shape of a plugin: a plain object
{ name, version, apply(api) }or a function(api, options) => void. A single entry point makes loading, testing, and typing simple. A name is needed for ordering, errors, and duplicates. - Extension points: pick one model and stay with it. Hooks with named stages (
beforeRequest,afterResponse), middleware (next()chain like Express and Koa), events (on('save')), or transforms (waterfall hooks where each plugin gets the previous result). Tapable and Rollup use hook types such as sequential, waterfall, and parallel. Choose by need: waterfall for data changes, parallel for side effects. - Ordering: define it. Use registration order by default, plus explicit
beforeandafteror numeric priority when needed. Document that order matters for waterfall hooks. - The API given to plugins: a narrow object with
hook(name, fn),getOption,logger, and helper methods. Do not pass the internal state or private classes, because anything exposed becomes a public contract. - Error handling: wrap each plugin call with the plugin's name in the error (
Error.causekeeps the original). Choose the policy: fail fast in development, isolate and continue in production for non-critical hooks, with a timeout for async hooks. - Lifecycle:
setup,disposeor teardown functions returned from install, so hot reload, tests, and unmounting do not leak listeners. Prevent double install. - Versioning: a
apiVersionorrequiresrange checked at install, a changelog for hook names and payloads, deprecation warnings before removal, and TypeScript types for the plugin API. - Security and trust: plugins run in the same realm with full power. For untrusted code use iframes, workers, or a ShadowRealm-like sandbox, with a message-based API. For first-party plugins, trust is fine but review the permissions.
- Performance: lazy-load plugins, keep hook dispatch cheap (arrays of functions, no per-call allocation), and skip empty hooks.
- Testing: provide a test harness and a way to create an isolated instance, so plugin authors can test without a global state.
- Discoverability: naming conventions (
mylib-plugin-*), a registry or documentation, and examples.
Trade-offs: more hooks give more freedom and more breaking changes. Start with few hooks, add them when real plugins need them, and keep core features out of plugins.
javascript
function createApp() {
const hooks = new Map();
const installed = new Map();
const disposers = [];
const run = async (name, value, ctx = {}) => {
for (const { plugin, fn } of hooks.get(name) ?? []) {
try {
const next = await fn(value, ctx);
if (next !== undefined) value = next;
} catch (error) {
throw new Error(`plugin "${plugin}" failed in hook "${name}"`, { cause: error });
}
}
return value;
};
return {
run,
use(plugin, options = {}) {
if (installed.has(plugin.name)) throw new Error(`plugin "${plugin.name}" is already installed`);
if (plugin.requires && plugin.requires > 2) throw new Error(`plugin "${plugin.name}" needs API version ${plugin.requires}`);
const api = {
options,
hook(name, fn, { priority = 0 } = {}) {
const list = hooks.get(name) ?? [];
list.push({ plugin: plugin.name, fn, priority });
list.sort((a, b) => b.priority - a.priority);
hooks.set(name, list);
},
};
const dispose = plugin.apply(api);
installed.set(plugin.name, plugin);
if (typeof dispose === 'function') disposers.push(dispose);
return this;
},
names: () => [...installed.keys()],
dispose: () => disposers.splice(0).forEach((fn) => fn()),
};
}
const trim = { name: 'trim', apply: (api) => api.hook('transform', (text) => text.trim()) };
const shout = { name: 'shout', apply: (api) => api.hook('transform', (text) => text.toUpperCase() + api.options.suffix) };
const early = { name: 'early', apply: (api) => api.hook('transform', (text) => text.replace('hello', 'hi'), { priority: 10 }) };
const logger = {
name: 'logger',
apply(api) {
api.hook('transform', (text) => void console.log(' logger saw:', JSON.stringify(text)), { priority: -5 });
return () => console.log(' logger cleaned up');
},
};
const broken = { name: 'broken', apply: (api) => api.hook('transform', () => { throw new TypeError('bad input'); }) };
(async () => {
const app = createApp().use(trim).use(shout, { suffix: '!' }).use(early).use(logger);
console.log('plugins:', app.names());
console.log('result:', await app.run('transform', ' hello world '));
try { app.use(trim); } catch (error) { console.log('duplicate:', error.message); }
try { app.use({ name: 'future', requires: 3, apply() {} }); } catch (error) { console.log('version:', error.message); }
app.use(broken);
try {
await app.run('transform', 'x');
} catch (error) {
console.log('error:', error.message, '| cause:', error.cause.name, error.cause.message);
}
console.log('unknown hook returns the input:', await app.run('other', 'same'));
app.dispose();
})();Run with Node.js v24.22.1 as js-189.js; two runs gave identical output. Output: plugins: [ 'trim', 'shout', 'early', 'logger' ] logger saw: "HI WORLD!" result: HI WORLD! duplicate: plugin "trim" is already installed version: plugin "future" needs API version 3 error: plugin "broken" failed in hook "transform" | cause: TypeError bad input unknown hook returns the input: same logger cleaned up
Key points
- One install entry point and a narrow, documented API object.
- Pick a model: hooks, middleware, events, or waterfall transforms; define order and error policy.
- Wrap plugin errors with the plugin name and cause; add timeouts for async hooks.
- Provide teardown, version checks, and deprecation paths.
- Do not expose internals; sandbox untrusted plugins.
Common mistakes
- Exposing internal objects to plugins and then being unable to change them.
- Leaving plugin order undefined while using waterfall hooks.
- Letting a plugin error fail with no plugin name in the message.
- No teardown, which leaks listeners in tests and hot reload.
Follow-ups
- When would you choose middleware over hooks?
- How would you sandbox untrusted plugins?
- How do you deprecate a hook?
Tips
- Ask what must stay stable before choosing a model.
- Cover errors, ordering, and teardown; they separate designs.
- Keep the plugin API small.