
Security Fundamentals
Turtles, Clams, and Cyber Threat Actors: Shell Usage
The Socket Threat Research Team uncovers how threat actors weaponize shell techniques across npm, PyPI, and Go ecosystems to maintain persistence and exfiltrate data.
before-after-hook
Advanced tools
asynchronous before/error/after hooks for internal functionality
The before-after-hook npm package allows developers to add before, after, and error hooks to JavaScript functions. This is particularly useful for adding custom pre-processing, post-processing, or error handling logic in a clean and organized manner. It can be used in both Node.js and browser environments.
Creating and using a single hook
This example demonstrates how to create a hook and attach before and after hooks to a function. The before hook logs a message before the main function runs, and the after hook logs a message after the main function completes.
const {Hook} = require('before-after-hook');
const hook = new Hook();
hook.before(addTask, async () => {
console.log('Before adding task');
});
hook.after(addTask, async () => {
console.log('After adding task');
});
async function addTask() {
console.log('Adding task');
}
hook(addTask, []).then(() => {
console.log('Task added');
});
Error handling with hooks
This example shows how to use the error hook to handle errors that may occur in the main function. The error hook logs the error message, providing a centralized way to handle errors.
const {Hook} = require('before-after-hook');
const hook = new Hook();
hook.error(addTask, async (error) => {
console.error('Error occurred:', error.message);
});
async function addTask() {
throw new Error('Failed to add task');
}
hook(addTask, []).catch(err => {
console.log('Error handling complete.');
});
Wrapping functions with multiple hooks
This example illustrates how to use HookCollection to manage multiple hooks for a single named operation. It demonstrates adding before, after, and error hooks for a 'save' operation, providing a comprehensive example of managing complex asynchronous operations.
const {HookCollection} = require('before-after-hook');
const hooks = new HookCollection();
hooks.before('save', async () => {
console.log('Before save');
});
hooks.after('save', async () => {
console.log('After save');
});
hooks.error('save', async (error) => {
console.error('Error during save:', error.message);
});
async function saveData() {
console.log('Saving data');
}
hooks('save', saveData, []).then(() => {
console.log('Data saved');
}).catch(err => {
console.log('Error handling complete.');
});
Similar to before-after-hook, async-hooks provides mechanisms to track asynchronous resources in Node.js. While async-hooks is more focused on the lifecycle and context of asynchronous operations, before-after-hook focuses on adding custom logic before, after, or on errors of specific functions.
This package allows for the use of asynchronous middleware patterns, similar to how before-after-hook allows for pre and post function execution logic. However, middleware-async is more tailored towards use in web server frameworks like Express, providing a more specific use case compared to the more general-purpose before-after-hook.
asynchronous hooks for internal functionality
Browsers |
Load before-after-hook directly from cdn.skypack.dev
|
---|---|
Node |
Install with
|
// instantiate singular hook API
const hook = new Hook.Singular();
// Create a hook
async function getData(options) {
try {
const result = await hook(fetchFromDatabase, options);
return handleData(result);
} catch (error) {
return handleGetError(error);
}
}
// register before/error/after hooks.
// The methods can be async or return a promise
hook.before(beforeHook);
hook.error(errorHook);
hook.after(afterHook);
getData({ id: 123 });
// instantiate hook collection API
const hookCollection = new Hook.Collection();
// Create a hook
async function getData(options) {
try {
const result = await hookCollection("get", fetchFromDatabase, options);
return handleData(result);
} catch (error) {
return handleGetError(error);
}
}
// register before/error/after hooks.
// The methods can be async or return a promise
hookCollection.before("get", beforeHook);
hookCollection.error("get", errorHook);
hookCollection.after("get", afterHook);
getData({ id: 123 });
There's no fundamental difference between the Hook.Singular
and Hook.Collection
hooks except for the fact that a hook from a collection requires you to pass along the name. Therefore the following explanation applies to both code snippets as described above.
The methods are executed in the following order
beforeHook
fetchFromDatabase
afterHook
handleData
beforeHook
can mutate options
before it’s passed to fetchFromDatabase
.
If an error is thrown in beforeHook
or fetchFromDatabase
then errorHook
is
called next.
If afterHook
throws an error then handleGetError
is called instead
of handleData
.
If errorHook
throws an error then handleGetError
is called next, otherwise
afterHook
and handleData
.
You can also use hook.wrap
to achieve the same thing as shown above (collection example):
hookCollection.wrap("get", async (getData, options) => {
await beforeHook(options);
try {
const result = getData(options);
} catch (error) {
await errorHook(error, options);
}
await afterHook(result, options);
});
The Hook.Singular
constructor has no options and returns a hook
instance with the
methods below:
const hook = new Hook.Singular();
Using the singular hook is recommended for TypeScript
The singular hook is a reference to a single hook. This means that there's no need to pass along any identifier (such as a name
as can be seen in the Hook.Collection API).
The API of a singular hook is exactly the same as a collection hook and we therefore suggest you read the Hook.Collection API and leave out any use of the name
argument. Just skip it like described in this example:
const hook = new Hook.Singular();
// good
hook.before(beforeHook);
hook.after(afterHook);
hook(fetchFromDatabase, options);
// bad
hook.before("get", beforeHook);
hook.after("get", afterHook);
hook("get", fetchFromDatabase, options);
The Hook.Collection
constructor has no options and returns a hookCollection
instance with the
methods below
const hookCollection = new Hook.Collection();
Use the api
property to return the public API:
That way you don’t need to expose the hookCollection() method to consumers of your library
Invoke before and after hooks. Returns a promise.
hookCollection(nameOrNames, method /*, options */);
Argument | Type | Description | Required |
---|---|---|---|
name | String or Array of Strings | Hook name, for example 'save' . Or an array of names, see example below. | Yes |
method | Function | Callback to be executed after all before hooks finished execution successfully. options is passed as first argument | Yes |
options | Object | Will be passed to all before hooks as reference, so they can mutate it | No, defaults to empty object ({} ) |
Resolves with whatever method
returns or resolves with.
Rejects with error that is thrown or rejected with by
method
Simple Example
hookCollection(
"save",
(record) => {
return store.save(record);
},
record
);
// shorter: hookCollection('save', store.save, record)
hookCollection.before("save", function addTimestamps(record) {
const now = new Date().toISOString();
if (record.createdAt) {
record.updatedAt = now;
} else {
record.createdAt = now;
}
});
Example defining multiple hooks at once.
hookCollection(
["add", "save"],
(record) => {
return store.save(record);
},
record
);
hookCollection.before("add", function addTimestamps(record) {
if (!record.type) {
throw new Error("type property is required");
}
});
hookCollection.before("save", function addTimestamps(record) {
if (!record.type) {
throw new Error("type property is required");
}
});
Defining multiple hooks is helpful if you have similar methods for which you want to define separate hooks, but also an additional hook that gets called for all at once. The example above is equal to this:
hookCollection(
"add",
(record) => {
return hookCollection(
"save",
(record) => {
return store.save(record);
},
record
);
},
record
);
Add before hook for given name.
hookCollection.before(name, method);
Argument | Type | Description | Required |
---|---|---|---|
name | String | Hook name, for example 'save' | Yes |
method | Function |
Executed before the wrapped method. Called with the hook’s
options argument. Before hooks can mutate the passed options
before they are passed to the wrapped method.
| Yes |
Example
hookCollection.before("save", function validate(record) {
if (!record.name) {
throw new Error("name property is required");
}
});
Add error hook for given name.
hookCollection.error(name, method);
Argument | Type | Description | Required |
---|---|---|---|
name | String | Hook name, for example 'save' | Yes |
method | Function |
Executed when an error occurred in either the wrapped method or a
before hook. Called with the thrown error
and the hook’s options argument. The first method
which does not throw an error will set the result that the after hook
methods will receive.
| Yes |
Example
hookCollection.error("save", (error, options) => {
if (error.ignore) return;
throw error;
});
Add after hook for given name.
hookCollection.after(name, method);
Argument | Type | Description | Required |
---|---|---|---|
name | String | Hook name, for example 'save' | Yes |
method | Function |
Executed after wrapped method. Called with what the wrapped method
resolves with the hook’s options argument.
| Yes |
Example
hookCollection.after("save", (result, options) => {
if (result.updatedAt) {
app.emit("update", result);
} else {
app.emit("create", result);
}
});
Add wrap hook for given name.
hookCollection.wrap(name, method);
Argument | Type | Description | Required |
---|---|---|---|
name | String | Hook name, for example 'save' | Yes |
method | Function | Receives both the wrapped method and the passed options as arguments so it can add logic before and after the wrapped method, it can handle errors and even replace the wrapped method altogether | Yes |
Example
hookCollection.wrap("save", async (saveInDatabase, options) => {
if (!record.name) {
throw new Error("name property is required");
}
try {
const result = await saveInDatabase(options);
if (result.updatedAt) {
app.emit("update", result);
} else {
app.emit("create", result);
}
return result;
} catch (error) {
if (error.ignore) return;
throw error;
}
});
See also: Test mock example
Removes hook for given name.
hookCollection.remove(name, hookMethod);
Argument | Type | Description | Required |
---|---|---|---|
name | String | Hook name, for example 'save' | Yes |
beforeHookMethod | Function |
Same function that was previously passed to hookCollection.before() , hookCollection.error() , hookCollection.after() or hookCollection.wrap()
| Yes |
Example
hookCollection.remove("save", validateRecord);
This library contains type definitions for TypeScript.
Singular
:import Hook from "before-after-hook";
type TOptions = { foo: string }; // type for options
type TResult = { bar: number }; // type for result
type TError = Error; // type for error
const hook = new Hook.Singular<TOptions, TResult, TError>();
hook.before((options) => {
// `options.foo` has `string` type
// not allowed
options.foo = 42;
// allowed
options.foo = "Forty-Two";
});
const hookedMethod = hook(
(options) => {
// `options.foo` has `string` type
// not allowed, because it does not satisfy the `R` type
return { foo: 42 };
// allowed
return { bar: 42 };
},
{ foo: "Forty-Two" }
);
You can choose not to pass the types for options, result or error. So, these are completely valid:
const hook = new Hook.Singular<O, R>();
const hook = new Hook.Singular<O>();
const hook = new Hook.Singular();
In these cases, the omitted types will implicitly be any
.
Collection
:Collection
also has strict type support. You can use it like this:
import { Hook } from "before-after-hook";
type HooksType = {
add: {
Options: { type: string };
Result: { id: number };
Error: Error;
};
save: {
Options: { type: string };
Result: { id: number };
};
read: {
Options: { id: number; foo: number };
};
destroy: {
Options: { id: number; foo: string };
};
};
const hooks = new Hook.Collection<HooksType>();
hooks.before("destroy", (options) => {
// `options.id` has `number` type
});
hooks.error("add", (err, options) => {
// `options.type` has `string` type
// `err` is `instanceof Error`
});
hooks.error("save", (err, options) => {
// `options.type` has `string` type
// `err` has type `any`
});
hooks.after("save", (result, options) => {
// `options.type` has `string` type
// `result.id` has `number` type
});
You can choose not to pass the types altogether. In that case, everything will implicitly be any
:
const hook = new Hook.Collection();
Alternative imports:
import { Singular, Collection } from "before-after-hook";
const hook = new Singular();
const hooks = new Collection();
Since version 1.4 the Hook
constructor has been deprecated in favor of returning Hook.Singular
in an upcoming breaking release.
Version 1.4 is still 100% backwards-compatible, but if you want to continue using hook collections, we recommend using the Hook.Collection
constructor instead before the next release.
For even more details, check out the PR.
If before-after-hook
is not for you, have a look at one of these alternatives:
FAQs
asynchronous before/error/after hooks for internal functionality
The npm package before-after-hook receives a total of 8,681,223 weekly downloads. As such, before-after-hook popularity was classified as popular.
We found that before-after-hook demonstrated a not healthy version release cadence and project activity because the last version was released 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 Fundamentals
The Socket Threat Research Team uncovers how threat actors weaponize shell techniques across npm, PyPI, and Go ecosystems to maintain persistence and exfiltrate data.
Security News
At VulnCon 2025, NIST scrapped its NVD consortium plans, admitted it can't keep up with CVEs, and outlined automation efforts amid a mounting backlog.
Product
We redesigned our GitHub PR comments to deliver clear, actionable security insights without adding noise to your workflow.