Implement a plugin system with hooks
Implement a plugin system with hooks in JavaScript: plugins subscribe to named hooks and the host can run them in series or wait for all. Node.js 24.
A plugin system lets other people extend an app without touching its code. The host exposes named hooks, and a plugin is an object that registers handlers for them.
class App {
#hooks = new Map();
use(plugin) {
plugin.install({ on: (name, fn) => this.#hooks.set(name, [...(this.#hooks.get(name) ?? []), fn]) });
return this;
}
async run(name, payload) {
for (const fn of this.#hooks.get(name) ?? []) payload = (await fn(payload)) ?? payload;
return payload;
}
}
const slugify = { install: ({ on }) => on('beforeSave', (post) => ({ ...post, slug: post.title.toLowerCase().replaceAll(' ', '-') })) };
const stamp = { install: ({ on }) => on('beforeSave', (post) => ({ ...post, saved: true })) };
const app = new App().use(slugify).use(stamp);
console.log(await app.run('beforeSave', { title: 'Hello World' }));{ title: 'Hello World', slug: 'hello-world', saved: true }install receives a small API object, not the app itself, so plugins can only add handlers. A handler returns the new payload, or nothing to keep the old one.
Handlers run in registration order, so one plugin can depend on another's work. Treat the hook names as a public contract and catch handler errors if plugins are third-party. The sample uses top-level await, so it runs as an ES module.