require-middleware
raw JSON → 1.0.0 verified Sat Apr 25 auth: no javascript
Inject middleware into Node.js require() calls before they hit the cache, file system, or native modules. Version 1.0.0 is the initial stable release. It allows intercepting and transforming modules at load time, useful for instrumentation, mocking, or polyfilling. Differentiates by operating at the require level rather than module-level hooks, providing a middleware pipeline similar to Express.
Common errors
error Error: Require middleware already wrapped ↓
cause Calling wrap() twice without intermediate unwrap().
fix
Call unwrap() before wrapping again, or conditionally wrap.
error Error: Cannot find module 'require-middleware' ↓
cause Package not installed or import path incorrect.
fix
Run npm install require-middleware and ensure import/require path is correct.
error TypeError: use is not a function ↓
cause Incorrect import; likely default import when named export exists.
fix
Use { use } from 'require-middleware'.
Warnings
breaking Only one wrapper can be active at a time; calling wrap() while already wrapped will error. ↓
fix Call unwrap() before wrap() again, or check if already wrapped.
breaking Middleware cannot be added after wrap() is called; use() must be called before wrap() ↓
fix Register all middleware via use() before calling wrap().
gotcha The middleware receives an object with 'filename' and 'exports', not the module's exports directly. Modify exports via mod.exports = ... ↓
fix Access mod.exports to modify the module's exports.
gotcha Relative require paths may be misaligned; the filename is absolute but the require call may be relative. ↓
fix Use path.relative or resolve manually if comparing paths.
Install
npm install require-middleware yarn add require-middleware pnpm add require-middleware Imports
- wrap wrong
const wrap = require('require-middleware').wrapcorrectimport { wrap } from 'require-middleware' - unwrap wrong
const { unwrap } = require('require-middleware');correctimport { unwrap } from 'require-middleware' - use wrong
import use from 'require-middleware';correctimport { use } from 'require-middleware'
Quickstart
import { wrap, unwrap, use } from 'require-middleware';
// Define a middleware that logs module loads
use((mod) => {
console.log(`Loading module: ${mod.filename}`);
return mod;
});
// Wrap require to enable middleware
wrap();
// Now require a module, middleware will run
const fs = require('fs'); // logs: Loading module: /path/to/fs.js
// Optionally unwrap to restore original require
unwrap();