
Security News
The Changelog Podcast: Practical Steps to Stay Safe on npm
Learn the essential steps every developer should take to stay secure on npm and reduce exposure to supply chain attacks.
enforceBeforeAfterdeprecatedHooksallowDeprecatednpm install hookified --save
This was built because we constantly wanted hooks and events extended on libraires we are building such as Keyv and Cacheable. This is a simple way to add hooks and events to your classes.
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super();
}
async myMethodEmittingEvent() {
this.emit('message', 'Hello World'); //using Emittery
}
//with hooks you can pass data in and if they are subscribed via onHook they can modify the data
async myMethodWithHooks() Promise<any> {
let data = { some: 'data' };
// do something
await this.hook('before:myMethod2', data);
return data;
}
}
You can even pass in multiple arguments to the hooks:
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super();
}
async myMethodWithHooks() Promise<any> {
let data = { some: 'data' };
let data2 = { some: 'data2' };
// do something
await this.hook('before:myMethod2', data, data2);
return data;
}
}
<script type="module">
import { Hookified } from 'https://cdn.jsdelivr.net/npm/hookified/dist/browser/index.js';
class MyClass extends Hookified {
constructor() {
super();
}
async myMethodEmittingEvent() {
this.emit('message', 'Hello World'); //using Emittery
}
//with hooks you can pass data in and if they are subscribed via onHook they can modify the data
async myMethodWithHooks() Promise<any> {
let data = { some: 'data' };
// do something
await this.hook('before:myMethod2', data);
return data;
}
}
</script>
if you are not using ESM modules, you can use the following:
<script src="https://cdn.jsdelivr.net/npm/hookified/dist/browser/index.global.js"></script>
<script>
class MyClass extends Hookified {
constructor() {
super();
}
async myMethodEmittingEvent() {
this.emit('message', 'Hello World'); //using Emittery
}
//with hooks you can pass data in and if they are subscribed via onHook they can modify the data
async myMethodWithHooks() Promise<any> {
let data = { some: 'data' };
// do something
await this.hook('before:myMethod2', data);
return data;
}
}
</script>
If set to true, errors thrown in hooks will be thrown. If set to false, errors will be only emitted.
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super({ throwHookErrors: true });
}
}
const myClass = new MyClass();
console.log(myClass.throwHookErrors); // true. because it is set in super
try {
myClass.onHook('error-event', async () => {
throw new Error('error');
});
await myClass.hook('error-event');
} catch (error) {
console.log(error.message); // error
}
myClass.throwHookErrors = false;
console.log(myClass.throwHookErrors); // false
If set, errors thrown in hooks will be logged to the logger. If not set, errors will be only emitted.
import { Hookified } from 'hookified';
import pino from 'pino';
const logger = pino(); // create a logger instance that is compatible with Logger type
class MyClass extends Hookified {
constructor() {
super({ logger });
}
async myMethodWithHooks() Promise<any> {
let data = { some: 'data' };
// do something
await this.hook('before:myMethod2', data);
return data;
}
}
const myClass = new MyClass();
myClass.onHook('before:myMethod2', async () => {
throw new Error('error');
});
// when you call before:myMethod2 it will log the error to the logger
await myClass.hook('before:myMethod2');
If set to true, enforces that all hook names must start with 'before' or 'after'. This is useful for maintaining consistent hook naming conventions in your application. Default is false.
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super({ enforceBeforeAfter: true });
}
}
const myClass = new MyClass();
console.log(myClass.enforceBeforeAfter); // true
// These will work fine
myClass.onHook('beforeSave', async () => {
console.log('Before save hook');
});
myClass.onHook('afterSave', async () => {
console.log('After save hook');
});
myClass.onHook('before:validation', async () => {
console.log('Before validation hook');
});
// This will throw an error
try {
myClass.onHook('customEvent', async () => {
console.log('This will not work');
});
} catch (error) {
console.log(error.message); // Hook event "customEvent" must start with "before" or "after" when enforceBeforeAfter is enabled
}
// You can also change it dynamically
myClass.enforceBeforeAfter = false;
myClass.onHook('customEvent', async () => {
console.log('This will work now');
});
The validation applies to all hook-related methods:
onHook(), addHook(), onHookEntry(), onHooks()prependHook(), onceHook(), prependOnceHook()hook(), callHook()getHooks(), removeHook(), removeHooks()Note: The beforeHook() and afterHook() helper methods automatically generate proper hook names and work regardless of the enforceBeforeAfter setting.
A Map of deprecated hook names to deprecation messages. When a deprecated hook is used, a warning will be emitted via the 'warn' event and logged to the logger (if available). Default is an empty Map.
import { Hookified } from 'hookified';
// Define deprecated hooks with custom messages
const deprecatedHooks = new Map([
['oldHook', 'Use newHook instead'],
['legacyMethod', 'This hook will be removed in v2.0'],
['deprecatedFeature', ''] // Empty message - will just say "deprecated"
]);
class MyClass extends Hookified {
constructor() {
super({ deprecatedHooks });
}
}
const myClass = new MyClass();
console.log(myClass.deprecatedHooks); // Map with deprecated hooks
// Listen for deprecation warnings
myClass.on('warn', (event) => {
console.log(`Deprecation warning: ${event.message}`);
// event.hook contains the hook name
// event.message contains the full warning message
});
// Using a deprecated hook will emit warnings
myClass.onHook('oldHook', () => {
console.log('This hook is deprecated');
});
// Output: Hook "oldHook" is deprecated: Use newHook instead
// Using a deprecated hook with empty message
myClass.onHook('deprecatedFeature', () => {
console.log('This hook is deprecated');
});
// Output: Hook "deprecatedFeature" is deprecated
// You can also set deprecated hooks dynamically
myClass.deprecatedHooks.set('anotherOldHook', 'Please migrate to the new API');
// Works with logger if provided
import pino from 'pino';
const logger = pino();
const myClassWithLogger = new Hookified({
deprecatedHooks,
logger
});
// Deprecation warnings will be logged to logger.warn
The deprecation warning system applies to all hook-related methods:
onHook(), addHook(), onHookEntry(), onHooks(), prependHook(), onceHook(), prependOnceHook()hook(), callHook()getHooks(), removeHook(), removeHooks()Deprecation warnings are emitted in two ways:
{ hook: string, message: string }logger.warn() if a logger is configured and has a warn methodControls whether deprecated hooks are allowed to be registered and executed. Default is true. When set to false, deprecated hooks will still emit warnings but will be prevented from registration and execution.
import { Hookified } from 'hookified';
const deprecatedHooks = new Map([
['oldHook', 'Use newHook instead']
]);
class MyClass extends Hookified {
constructor() {
super({ deprecatedHooks, allowDeprecated: false });
}
}
const myClass = new MyClass();
console.log(myClass.allowDeprecated); // false
// Listen for deprecation warnings (still emitted even when blocked)
myClass.on('warn', (event) => {
console.log(`Warning: ${event.message}`);
});
// Try to register a deprecated hook - will emit warning but not register
myClass.onHook('oldHook', () => {
console.log('This will never execute');
});
// Output: Warning: Hook "oldHook" is deprecated: Use newHook instead
// Verify hook was not registered
console.log(myClass.getHooks('oldHook')); // undefined
// Try to execute a deprecated hook - will emit warning but not execute
await myClass.hook('oldHook');
// Output: Warning: Hook "oldHook" is deprecated: Use newHook instead
// (but no handlers execute)
// Non-deprecated hooks work normally
myClass.onHook('validHook', () => {
console.log('This works fine');
});
console.log(myClass.getHooks('validHook')); // [handler function]
// You can dynamically change the setting
myClass.allowDeprecated = true;
// Now deprecated hooks can be registered and executed
myClass.onHook('oldHook', () => {
console.log('Now this works');
});
console.log(myClass.getHooks('oldHook')); // [handler function]
Behavior when allowDeprecated is false:
onHook, addHook, prependHook, etc.) will emit warnings but skip registrationhook, callHook) will emit warnings but skip executiongetHooks, removeHook) will emit warnings and return undefined/skip operationsallowDeprecated settingUse cases:
allowDeprecated: true to maintain functionality while seeing warningsallowDeprecated: false to ensure no deprecated hooks are accidentally usedSubscribe to a hook event.
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super();
}
async myMethodWithHooks() Promise<any> {
let data = { some: 'data' };
// do something
await this.hook('before:myMethod2', data);
return data;
}
}
const myClass = new MyClass();
myClass.onHook('before:myMethod2', async (data) => {
data.some = 'new data';
});
This allows you to create a hook with the HookEntry type which includes the event and handler. This is useful for creating hooks with a single object.
import { Hookified, HookEntry } from 'hookified';
class MyClass extends Hookified {
constructor() {
super();
}
async myMethodWithHooks() Promise<any> {
let data = { some: 'data' };
// do something
await this.hook('before:myMethod2', data);
return data;
}
}
const myClass = new MyClass();
myClass.onHookEntry({
event: 'before:myMethod2',
handler: async (data) => {
data.some = 'new data';
},
});
This is an alias for .onHook(eventName, handler) for backwards compatibility.
Subscribe to multiple hook events at once
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super();
}
async myMethodWithHooks() Promise<any> {
let data = { some: 'data' };
await this.hook('before:myMethodWithHooks', data);
// do something here with the data
data.some = 'new data';
await this.hook('after:myMethodWithHooks', data);
return data;
}
}
const myClass = new MyClass();
const hooks = [
{
event: 'before:myMethodWithHooks',
handler: async (data) => {
data.some = 'new data1';
},
},
{
event: 'after:myMethodWithHooks',
handler: async (data) => {
data.some = 'new data2';
},
},
];
Subscribe to a hook event once.
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super();
}
async myMethodWithHooks() Promise<any> {
let data = { some: 'data' };
// do something
await this.hook('before:myMethod2', data);
return data;
}
}
const myClass = new MyClass();
myClass.onHookOnce('before:myMethod2', async (data) => {
data.some = 'new data';
});
myClass.myMethodWithHooks();
console.log(myClass.hooks.length); // 0
Subscribe to a hook event before all other hooks.
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super();
}
async myMethodWithHooks() Promise<any> {
let data = { some: 'data' };
// do something
await this.hook('before:myMethod2', data);
return data;
}
}
const myClass = new MyClass();
myClass.onHook('before:myMethod2', async (data) => {
data.some = 'new data';
});
myClass.preHook('before:myMethod2', async (data) => {
data.some = 'will run before new data';
});
Subscribe to a hook event before all other hooks. After it is used once it will be removed.
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super();
}
async myMethodWithHooks() Promise<any> {
let data = { some: 'data' };
// do something
await this.hook('before:myMethod2', data);
return data;
}
}
const myClass = new MyClass();
myClass.onHook('before:myMethod2', async (data) => {
data.some = 'new data';
});
myClass.preHook('before:myMethod2', async (data) => {
data.some = 'will run before new data';
});
Unsubscribe from a hook event.
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super();
}
async myMethodWithHooks() Promise<any> {
let data = { some: 'data' };
// do something
await this.hook('before:myMethod2', data);
return data;
}
}
const myClass = new MyClass();
const handler = async (data) => {
data.some = 'new data';
};
myClass.onHook('before:myMethod2', handler);
myClass.removeHook('before:myMethod2', handler);
Unsubscribe from multiple hooks.
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super();
}
async myMethodWithHooks() Promise<any> {
let data = { some: 'data' };
await this.hook('before:myMethodWithHooks', data);
// do something
data.some = 'new data';
await this.hook('after:myMethodWithHooks', data);
return data;
}
}
const myClass = new MyClass();
const hooks = [
{
event: 'before:myMethodWithHooks',
handler: async (data) => {
data.some = 'new data1';
},
},
{
event: 'after:myMethodWithHooks',
handler: async (data) => {
data.some = 'new data2';
},
},
];
myClass.onHooks(hooks);
// remove all hooks
myClass.removeHook(hooks);
Run a hook event.
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super();
}
async myMethodWithHooks() Promise<any> {
let data = { some: 'data' };
// do something
await this.hook('before:myMethod2', data);
return data;
}
}
in this example we are passing multiple arguments to the hook:
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super();
}
async myMethodWithHooks() Promise<any> {
let data = { some: 'data' };
let data2 = { some: 'data2' };
// do something
await this.hook('before:myMethod2', data, data2);
return data;
}
}
const myClass = new MyClass();
myClass.onHook('before:myMethod2', async (data, data2) => {
data.some = 'new data';
data2.some = 'new data2';
});
await myClass.myMethodWithHooks();
This is an alias for .hook(eventName, ...args) for backwards compatibility.
This is a helper function that will prepend a hook name with before:.
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super();
}
async myMethodWithHooks() Promise<any> {
let data = { some: 'data' };
// the event name will be `before:myMethod2`
await this.beforeHook('myMethod2', data);
return data;
}
}
This is a helper function that will prepend a hook name with after:.
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super();
}
async myMethodWithHooks() Promise<any> {
let data = { some: 'data' };
// the event name will be `after:myMethod2`
await this.afterHook('myMethod2', data);
return data;
}
}
Get all hooks.
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super();
}
async myMethodWithHooks() Promise<any> {
let data = { some: 'data' };
// do something
await this.hook('before:myMethod2', data);
return data;
}
}
const myClass = new MyClass();
myClass.onHook('before:myMethod2', async (data) => {
data.some = 'new data';
});
console.log(myClass.hooks);
Get all hooks for an event.
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super();
}
async myMethodWithHooks() Promise<any> {
let data = { some: 'data' };
// do something
await this.hook('before:myMethod2', data);
return data;
}
}
const myClass = new MyClass();
myClass.onHook('before:myMethod2', async (data) => {
data.some = 'new data';
});
console.log(myClass.getHooks('before:myMethod2'));
Clear all hooks for an event.
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super();
}
async myMethodWithHooks() Promise<any> {
let data = { some: 'data' };
// do something
await this.hook('before:myMethod2', data);
return data;
}
}
const myClass = new MyClass();
myClass.onHook('before:myMethod2', async (data) => {
data.some = 'new data';
});
myClass.clearHooks('before:myMethod2');
If set to true, errors emitted as error will be thrown if there are no listeners. If set to false, errors will be only emitted.
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super();
}
async myMethodWithHooks() Promise<any> {
let data = { some: 'data' };
// do something
await this.hook('before:myMethod2', data);
return data;
}
}
Subscribe to an event.
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super();
}
async myMethodEmittingEvent() {
this.emit('message', 'Hello World');
}
}
const myClass = new MyClass();
myClass.on('message', (message) => {
console.log(message);
});
Unsubscribe from an event.
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super();
}
async myMethodEmittingEvent() {
this.emit('message', 'Hello World');
}
}
const myClass = new MyClass();
myClass.on('message', (message) => {
console.log(message);
});
myClass.off('message', (message) => {
console.log(message);
});
Emit an event.
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super();
}
async myMethodEmittingEvent() {
this.emit('message', 'Hello World');
}
}
Get all listeners for an event.
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super();
}
async myMethodEmittingEvent() {
this.emit('message', 'Hello World');
}
}
const myClass = new MyClass();
myClass.on('message', (message) => {
console.log(message);
});
console.log(myClass.listeners('message'));
Remove all listeners for an event.
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super();
}
async myMethodEmittingEvent() {
this.emit('message', 'Hello World');
}
}
const myClass = new MyClass();
myClass.on('message', (message) => {
console.log(message);
});
myClass.removeAllListeners('message');
Set the maximum number of listeners and will truncate if there are already too many.
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super();
}
async myMethodEmittingEvent() {
this.emit('message', 'Hello World');
}
}
const myClass = new MyClass();
myClass.setMaxListeners(1);
myClass.on('message', (message) => {
console.log(message);
});
myClass.on('message', (message) => {
console.log(message);
}); // this will not be added and console warning
console.log(myClass.listenerCount('message')); // 1
Subscribe to an event once.
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super();
}
}
const myClass = new MyClass();
myClass.once('message', (message) => {
console.log(message);
});
myClass.emit('message', 'Hello World');
myClass.emit('message', 'Hello World'); // this will not be called
Prepend a listener to an event. This will be called before any other listeners.
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super();
}
}
const myClass = new MyClass();
myClass.prependListener('message', (message) => {
console.log(message);
});
Prepend a listener to an event once. This will be called before any other listeners.
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super();
}
}
const myClass = new MyClass();
myClass.prependOnceListener('message', (message) => {
console.log(message);
});
myClass.emit('message', 'Hello World');
Get all event names.
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super();
}
}
const myClass = new MyClass();
myClass.on('message', (message) => {
console.log(message);
});
console.log(myClass.eventNames());
Get the count of listeners for an event or all events if evenName not provided.
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super();
}
}
const myClass = new MyClass();
myClass.on('message', (message) => {
console.log(message);
});
console.log(myClass.listenerCount('message')); // 1
Get all listeners for an event or all events if evenName not provided.
import { Hookified } from 'hookified';
class MyClass extends Hookified {
constructor() {
super();
}
}
const myClass = new MyClass();
myClass.on('message', (message) => {
console.log(message);
});
console.log(myClass.rawListeners('message'));
We are doing very simple benchmarking to see how this compares to other libraries using tinybench. This is not a full benchmark but just a simple way to see how it performs. Our goal is to be as close or better than the other libraries including native (EventEmitter).
| name | summary | ops/sec | time/op | margin | samples |
|---|---|---|---|---|---|
| Hookified (v1.12.1) | 🥇 | 5M | 243ns | ±0.89% | 4M |
| Hookable (v5.5.3) | -69% | 1M | 835ns | ±2.23% | 1M |
This shows how on par hookified is to the native EventEmitter and popular eventemitter3. These are simple emitting benchmarks to see how it performs.
| name | summary | ops/sec | time/op | margin | samples |
|---|---|---|---|---|---|
| Hookified (v1.12.1) | 🥇 | 12M | 89ns | ±2.56% | 11M |
| EventEmitter3 (v5.0.1) | -1.7% | 12M | 91ns | ±3.31% | 11M |
| EventEmitter (v20.17.0) | -4% | 11M | 92ns | ±0.38% | 11M |
| Emittery (v1.2.0) | -91% | 1M | 1µs | ±1.59% | 993K |
Note: the EventEmitter version is Nodejs versioning.
Hookified is written in TypeScript and tests are written in vitest. To run the tests, use the following command:
To setup the environment and run the tests:
pnpm i && pnpm test
Note that we are using pnpm as our package manager. If you don't have it installed, you can install it globally with:
npm install -g pnpm
To contribute follow the Contributing Guidelines and Code of Conduct.
pnpm i && pnpm test
Note that we are using pnpm as our package manager. If you don't have it installed, you can install it globally with:
npm install -g pnpm
To contribute follow the Contributing Guidelines and Code of Conduct.
FAQs
Event Emitting and Middleware Hooks
The npm package hookified receives a total of 2,554,833 weekly downloads. As such, hookified popularity was classified as popular.
We found that hookified demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
Learn the essential steps every developer should take to stay secure on npm and reduce exposure to supply chain attacks.

Security News
Experts push back on new claims about AI-driven ransomware, warning that hype and sponsored research are distorting how the threat is understood.

Security News
Ruby's creator Matz assumes control of RubyGems and Bundler repositories while former maintainers agree to step back and transfer all rights to end the dispute.