The Problem: Tightly-Coupled Code
If you've built a few non-trivial applications in Node.js, you've likely run into a common problem: as your application grows, different parts become increasingly tangled together. Modifying one component often has unintended side effects on another. How can we allow different parts of our application to interact without being so tightly coupled?
For years, the WordPress community has had an elegant solution: the Hooks system. It provides two main components: Actions and Filters.
- Actions allow you to execute code at specific points in your application's lifecycle.
- Filters allow you to modify data that is being passed between different parts of your code.
This system is the backbone of WordPress's famous extensibility. I wanted to bring this powerful, battle-tested pattern to the Node.js ecosystem.
The Solution: node-hooker
Today, I'm excited to launch node-hooker
, a zero-dependency library that faithfully implements the WordPress Hooks API for Node.js.
It's a simple, lightweight, and powerful way to build decoupled, extensible architectures in your JavaScript applications.
Key Features
-
Full WordPress Hook API compatibility: All the functions you'd expect are there:
add_action
,do_action
,add_filter
,apply_filters
,remove_action
,did_action
, etc. - Zero dependencies: It won't add any bloat to your project.
- Browser Support: It includes a UMD bundle, so you can use the exact same event system on the client-side.
- Easy to use: The API is intuitive and well-documented.
How It Works: A Quick Example
Here’s a quick look at how you might use node-hooker
.
const hooker = require('node-hooker');
// Somewhere in your user authentication code
function handleUserLogin(user) {
console.log(`User ${user.name} logged in.`);
// Announce that a user has logged in.
// Other parts of the app can "hook" into this event.
hooker.do_action('user_logged_in', user);
}
// Somewhere else, maybe in an analytics or notifications module
function sendWelcomeEmail(user) {
console.log(`Sending a welcome email to ${user.email}...`);
}
// "Hook" the email function to the user login event.
hooker.add_action('user_logged_in', sendWelcomeEmail);
// Now, when you call the login handler...
handleUserLogin({ name: 'Alex', email: 'alex@example.com' });
`
Output:
User Alex logged in.
Sending a welcome email to alex@example.com...
Notice how the handleUserLogin
function doesn't need to know anything about sending emails. It just announces that an event happened. This makes your code incredibly modular and easy to test and maintain.
Check It Out!
I'm really proud of how node-hooker
turned out, and I believe it can be a valuable tool for many Node.js developers.
You can find the full source code, documentation, and more examples on GitHub.
➡️ https://github.com/mamedul/node-hooker
➡️ https://mamedul.github.io/node-hooker
If you find it useful, please consider giving it a star on GitHub! Thanks for reading.
Top comments (0)