In Node.js 24, how do `module.registerHooks()` resolve and load hooks customise module loading, and how do you make them cover the whole application?
answer
- where a specifier points, then what it contains
- next function or shortCircuit
- last registered runs first
- preload with --import before the entry
basics
~20 smodule.registerHooks() installs synchronous, in-thread hooks: resolve maps a specifier to a URL and load returns that URL's format and source. Each must call the next hook or return shortCircuit: true. Preload the registering file with --import so hooks precede the entry point.
solid answer
~40 sIn Node.js 24, `module.registerHooks({ resolve, load })` adds synchronous hooks that run on the loading thread for both `import` and `require()`. `resolve(specifier, context, nextResolve)` returns `{ url }` and optionally a `format` hint; `load(url, context, nextLoad)` returns `{ format, source }`, where `format` can be `'module'`, `'commonjs'`, `'json'`, `'module-typescript'` and others. Hooks chain last-in, first-out: each one either calls `next*()` or returns `shortCircuit: true`, otherwise Node throws. To cover the whole app, register them from a file preloaded with `node --import ./hooks.mjs app.mjs`; registering in the entry module and then statically importing the app misses it, because static imports run first. The older `module.register()` runs async hooks on a separate thread and is documentation-deprecated since v24.15.0.
code
javascript · 18 lines// text-hooks.mjs
import { registerHooks } from 'node:module';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
registerHooks({
load(url, context, nextLoad) {
if (url.endsWith('.txt')) {
const text = readFileSync(fileURLToPath(url), 'utf8');
return {
format: 'module',
source: `export default ${JSON.stringify(text)};`,
shortCircuit: true,
};
}
return nextLoad(url, context);
},
});go deeper
Recall that Node lets code intercept resolving and loading modules, and that hooks must be registered before the modules they should affect.
Explain resolve versus load, what each returns, and why a preload flag is needed to register before the entry's static imports.
Show the chaining contract, the LIFO order, the shortCircuit rule, and why registerHooks() replaced the off-thread module.register() for new code.
Judge when runtime hooks are worth their per-start cost versus building ahead, and set a team rule for where instrumentation and transpilation belong.
## What customization hooks are Every `import` and every `require()` in Node.js passes through two internal steps. **Resolution** turns a specifier such as `'./config.yaml'` or `'some-package'` into an absolute URL. **Loading** reads that URL and decides its **format** (ES module, CommonJS, JSON, WebAssembly and so on) and its **source** text. Customization hooks let your code sit in front of either step. Typical uses are loading files Node does not understand (YAML, text, a different language) by transpiling them in `load`, redirecting or mocking specifiers in `resolve`, and instrumentation that needs to see every module. ## Two APIs, one recommended | | `module.registerHooks()` | `module.register()` | |---|---|---| | Hook style | synchronous functions passed inline | a module exporting async functions | | Where hooks run | the same thread as the modules | a separate loader thread | | CommonJS `require()` | covered | several documented gaps | | Status in Node 24 | release candidate since v24.13.1 | documentation-deprecated since v24.15.0 (DEP0205) | The documentation recommends `registerHooks()` in most cases. The asynchronous hooks pay for inter-thread messaging, cannot touch the modules' global state directly, miss `require` functions made with `module.createRequire()`, and can cause CommonJS sources to be loaded more than once. The Node 26 documentation turns DEP0205 into a runtime deprecation, so new code should not start on `register()`. ## The two hook functions **`resolve(specifier, context, nextResolve)`** - `context` carries `conditions` (the export conditions in effect), `importAttributes` and `parentURL`. - Return an object with `url`, optionally a `format` hint for the load step, and `shortCircuit`. - To keep default behaviour while changing something, call `nextResolve(specifier, context)` with modified arguments; to add conditions, pass every original condition plus yours. **`load(url, context, nextLoad)`** - Return `format` and `source`. Valid final formats include `'module'`, `'commonjs'`, `'json'`, `'wasm'`, `'builtin'`, `'addon'` and the TypeScript formats `'module-typescript'` and `'commonjs-typescript'`. - You can call `nextLoad()` to get the original bytes and then transform them, or supply source of your own. ## Chaining rules 1. Hooks form a chain ending at Node's default implementation, which is always present. 2. Calling `registerHooks()` again adds to the chain; the **last registered runs first** (LIFO). 3. A hook must either call its `next` function or return `shortCircuit: true`. Returning without doing either, or returning an object missing a required property, throws, which protects against accidentally broken chains. 4. The returned object has `deregister()`, which removes those hooks for later loads. 5. If a `resolve` hook returns a `format`, a custom `load` hook is required, even one that only passes the value on to `nextLoad()`, because the load chain decides the final format. 6. Import attributes are part of the module cache key, so a `resolve` hook that wants a module cached under different attributes returns an `importAttributes` object. Because synchronous hooks run on the loading thread, they can share state with application code through ordinary variables, which is exactly what the off-thread `module.register()` hooks could not do without message channels and atomics. ## Making hooks apply to the whole application Hooks only affect modules loaded **after** they are registered. That makes registration timing the most common bug: - **Preload with a flag.** `node --import ./hooks.mjs app.mjs` (or `--require ./hooks.cjs`) runs the registering file before the entry point. `--require` preloads run before `--import` preloads, and repeated `--import` preloads run in order, starting with any given in `NODE_OPTIONS`. - **Beware static imports in the registering module.** A static `import './app.mjs'` is evaluated before any code in the importing module, including the `registerHooks()` call, wherever the line appears. Load the app with dynamic `import()` (or `require()`) after registering. - **Inline registration.** `--import` also accepts a `data:` URL, so a short `registerHooks()` call can be preloaded without a separate file. - **Worker threads.** Synchronous hooks are not inherited by `worker_threads` by themselves; registering from a file preloaded with `--import` or `--require` reaches workers because they inherit `process.execArgv` by default. ## Performance and production use The documentation is explicit that transpiling in a `load` hook is slower than transpiling before Node starts and recommends transpiler hooks for development and testing. Every loaded file pays the hook cost on every start. In production, prefer shipping JavaScript, or Node's built-in type stripping, and keep hooks for genuine runtime needs such as instrumentation or custom formats.
- Two libraries each call `registerHooks()` with a resolve hook; in what order do they run, and what happens if one forgets to call `nextResolve`?They run last-in, first-out: the most recently registered resolve runs first and its `nextResolve` reaches the earlier one, then Node's default. A hook that neither calls `nextResolve` nor returns `shortCircuit: true` makes Node throw, so the broken chain surfaces at once instead of silently skipping the other library.
- Why might a `load` hook that compiles a custom format be fine in tests but a poor choice in production on Node 24?Transformation then happens on every process start for every matching file, adding startup latency and CPU at exactly the moment a replica is trying to become ready. Node's documentation says transpiling before Node runs is more performant and recommends transpiler hooks for development and testing. Shipping prebuilt output removes that per-start cost.
- Calling registerHooks() at the top of the entry affects its static imports.
- The first registered hook runs first in the chain.
- A resolve hook can return without nextResolve and without shortCircuit.
- module.register() is the recommended hook API in Node 24.
- Synchronous hooks reach worker threads however they were registered.
Assumes Node.js 24: registerHooks() is a release candidate since v24.13.1 and module.register() is documentation-deprecated since v24.15.0 (runtime-deprecated in 26).