From 4e9c9a543c65f00f351ba53c7a97666379865e2d Mon Sep 17 00:00:00 2001 From: Geoffrey Booth Date: Mon, 9 Nov 2026 07:55:14 -0800 Subject: [PATCH 1/4] modules: add guide for migrating from module.register() Node.js 27 removes `module.register()` and the `--experimental-loader` and `--loader` flags (DEP0205). Explain how to move to `module.registerHooks()`, what behaves differently, and what to use when hooks need asynchronous work (`module-register-ponyfill` or `everysync`). Co-Authored-By: Claude Sonnet 5.5 --- .../modules/migrating-from-module-register.md | 264 ++++++++++++++++++ site.json | 4 + 2 files changed, 268 insertions(+) create mode 100644 pages/modules/migrating-from-module-register.md diff --git a/pages/modules/migrating-from-module-register.md b/pages/modules/migrating-from-module-register.md new file mode 100644 index 0000000..7519bd3 --- /dev/null +++ b/pages/modules/migrating-from-module-register.md @@ -0,0 +1,264 @@ +--- +authors: GeoffreyBooth +--- + +# Migrating from `module.register()` to `module.registerHooks()` + +Node.js 27 removes `module.register()` and the `--experimental-loader` and `--loader` flags ([DEP0205](https://nodejs.org/api/deprecations.html#dep0205-moduleregister)). These provided _asynchronous_ module customization hooks, which ran on a separate loader thread. They were documented as experimental, deprecated in the docs in Node.js 24.15.0 and 25.9.0, and began printing a runtime warning in Node.js 26.0.0. + +[`module.registerHooks()`](https://nodejs.org/api/module.html#moduleregisterhooksoptions) is the replacement. It takes the same kinds of hooks (`resolve` and `load`), but they are synchronous and run on the thread that loads your modules. In most cases that makes them simpler to write and faster to run. + +## Pick your path + +| Your hooks… | Do this | +| ------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| can run synchronously on the main thread (most can) | Rewrite them for `registerHooks()`, as described [below](#rewriting-your-hooks). | +| depend on asynchronous work, and you can’t or don’t want to rewrite them | Use [`module-register-ponyfill`](https://github.com/joyeecheung/module-register-ponyfill), a drop-in `register()` built on `registerHooks()` and a worker thread. | +| need their own off-thread design | Build it on `registerHooks()` plus a worker; [`everysync`](https://github.com/mcollina/everysync) turns async worker APIs into synchronous calls. | + +`registerHooks()` is available in Node.js 22.15.0 and later (and 23.5.0 and later). If your package supports older versions, feature-detect it: + +```js +import module from 'node:module'; + +if (typeof module.registerHooks === 'function') { + module.registerHooks({ resolve, load }); +} else { + module.register('./hooks.mjs', import.meta.url); +} +``` + +## Rewriting your hooks + +An asynchronous hooks module, registered with `register()`: + +```js +// hooks.mjs +export async function resolve(specifier, context, nextResolve) { + if (specifier === 'virtual:greeting') { + return { url: 'virtual:greeting', shortCircuit: true }; + } + return nextResolve(specifier, context); +} + +export async function load(url, context, nextLoad) { + if (url === 'virtual:greeting') { + return { + format: 'module', + source: 'export default "hello"', + shortCircuit: true, + }; + } + return nextLoad(url, context); +} +``` + +```js +// register.mjs +import { register } from 'node:module'; + +register('./hooks.mjs', import.meta.url); +``` + +The same hooks, registered with `registerHooks()`: + +```js +// register.mjs +import { registerHooks } from 'node:module'; + +registerHooks({ + resolve(specifier, context, nextResolve) { + if (specifier === 'virtual:greeting') { + return { url: 'virtual:greeting', shortCircuit: true }; + } + return nextResolve(specifier, context); + }, + load(url, context, nextLoad) { + if (url === 'virtual:greeting') { + return { + format: 'module', + source: 'export default "hello"', + shortCircuit: true, + }; + } + return nextLoad(url, context); + }, +}); +``` + +The hook functions have the same names, arguments and return values. What changed: + +- Remove `async` and `await`. `nextResolve()` and `nextLoad()` return their results directly. +- Pass the hooks straight to `registerHooks()` instead of exporting them from a separate module, so there is no specifier or `parentURL` to resolve. You can still keep them in their own file and `import` them. + +Run your app with the registration file preloaded, the same way you did before: + +```bash +node --import ./register.mjs app.mjs +``` + +## Replacing `--loader` and `--experimental-loader` + +These flags took a module that exported hooks. Replace the flag with `--import` and a small file that registers them: + +```bash +# Before (removed) +node --experimental-loader ./hooks.mjs app.mjs + +# After +node --import ./register.mjs app.mjs +``` + +Running Node.js 27 with either flag fails with `bad option: --loader` (or `--experimental-loader`). + +## What behaves differently + +### Hooks run on the main thread + +Asynchronous hooks had their own thread and global scope, so they passed data through `initialize()`, the `data` option and message ports. Synchronous hooks share your application’s thread and globals, so none of that is needed. Use a closure or module-level state instead: + +```js +import { registerHooks } from 'node:module'; + +const prefix = '>> '; // was passed through `initialize({ prefix })` + +registerHooks({ + resolve(specifier, context, nextResolve) { + console.log(prefix + 'resolving', specifier); + return nextResolve(specifier, context); + }, +}); +``` + +There is no `initialize` hook, `data` option or `transferList` option. A slow hook now blocks your application instead of a background thread, so keep them fast. + +### Hooks can’t be asynchronous + +If a hook awaited something, such as a file read, replace it with a synchronous equivalent: + +```js +import { registerHooks } from 'node:module'; +import { readFileSync } from 'node:fs'; + +registerHooks({ + load(url, context, nextLoad) { + if (url.endsWith('.txt')) { + return { + format: 'module', + shortCircuit: true, + source: `export default ${JSON.stringify(readFileSync(new URL(url), 'utf8'))};`, + }; + } + return nextLoad(url, context); + }, +}); +``` + +If the work can’t be made synchronous (a network request, for example), see [Hooks that need asynchronous work](#hooks-that-need-asynchronous-work). + +## Hooks that need asynchronous work + +Two options keep the asynchronous work off your main thread. + +### Keep your hooks module as it is + +[`module-register-ponyfill`](https://github.com/joyeecheung/module-register-ponyfill) provides `register()` on top of `registerHooks()`, a worker thread and `Atomics`, so an existing hooks module works unchanged. Install it, then replace `import { register } from 'node:module'` with an import from the package: + +```js +// register.mjs +import { register } from 'module-register-ponyfill'; + +register('./hooks.mjs', import.meta.url); +``` + +### Build a bridge with `everysync` + +[`everysync`](https://github.com/mcollina/everysync) lets synchronous code call an asynchronous function that runs in a worker thread: the caller blocks until the worker’s promise settles. That is what a synchronous `load` hook needs to fetch modules from a URL, for example. + +First, the worker exposes the asynchronous work: + +```js +// fetch-worker.mjs +import { wire } from 'everysync'; +import { workerData } from 'node:worker_threads'; + +wire(workerData.buffer, { + async fetchText(url) { + const response = await fetch(url); + return await response.text(); + }, +}); + +// Keep the worker's event loop alive. +setInterval(() => {}, 100000); +``` + +Then the registration file starts the worker and calls it from the hooks as if it were synchronous: + +```js +// register.mjs +import { registerHooks } from 'node:module'; +import { Worker } from 'node:worker_threads'; +import { makeSync } from 'everysync'; + +const buffer = new SharedArrayBuffer(1024, { + maxByteLength: 64 * 1024 * 1024, +}); +const worker = new Worker(new URL('./fetch-worker.mjs', import.meta.url), { + workerData: { buffer }, + execArgv: [], // Don't re-run this file (via --import) inside the worker. +}); +worker.unref(); // Don't let the worker keep the process alive. +const { fetchText } = makeSync(buffer); + +registerHooks({ + resolve(specifier, context, nextResolve) { + if (specifier.startsWith('https://')) { + return { url: specifier, shortCircuit: true }; + } + return nextResolve(specifier, context); + }, + load(url, context, nextLoad) { + if (url.startsWith('https://')) { + return { format: 'module', source: fetchText(url), shortCircuit: true }; + } + return nextLoad(url, context); + }, +}); +``` + +```bash +node --import ./register.mjs app.mjs +``` + +Two details matter. Pass `execArgv: []` when you preload the registration file with `--import`, because workers inherit your flags and would otherwise run `register.mjs` themselves and start another worker (`makeSync()` then fails with “The initialization timed out”). And remember that the calling thread is blocked while the worker waits on the network, so this suits tooling and development more than hot paths. + +### Hooks now apply to `require()` too + +Asynchronous hooks did not affect every `require()` call in a CommonJS module graph. Synchronous hooks run for `import`, `require()` and `createRequire()`, so a hook that previously only saw `import` will now also see CommonJS loads. If your hook assumes every module is ESM, check `context.format` or `context.conditions`. + +### Workers don’t inherit hooks + +Hooks registered with `registerHooks()` apply only to the thread that registered them. To use them in worker threads, either call `registerHooks()` in each worker, or register them in a file preloaded with `--import` (or `--require`); workers inherit those flags through `process.execArgv`: + +```bash +node --import ./register.mjs app.mjs +``` + +### Register before loading the modules you want to customize + +As before, hooks only affect modules loaded after they are registered. Preloading with `--import` guarantees this. If you register inside your application, load the customized modules afterward with a dynamic `import()`: + +```js +import './register.mjs'; + +const { default: greeting } = await import('virtual:greeting'); +``` + +## Troubleshooting + +- `bad option: --loader` or `bad option: --experimental-loader`: see [Replacing `--loader`](#replacing---loader-and---experimental-loader). +- `SyntaxError: The requested module 'node:module' does not provide an export named 'register'`, or `module.register is not a function`: switch to `registerHooks()`, as described [above](#rewriting-your-hooks). +- A hook that worked before now fails with `Promise` or `await` errors: it is probably returning a promise from a synchronous hook. Remove `async`. + +For the full hook reference, including the `context` objects and every return value, see the [`module` API documentation](https://nodejs.org/api/module.html#customization-hooks). diff --git a/site.json b/site.json index 1515874..f880183 100644 --- a/site.json +++ b/site.json @@ -351,6 +351,10 @@ { "link": "/learn/modules/abi-stability", "label": "ABI Stability" + }, + { + "link": "/learn/modules/migrating-from-module-register", + "label": "Migrating from module.register()" } ] }, From 4b2f22ceb4875ace2fc3c1d921ad469d582896fb Mon Sep 17 00:00:00 2001 From: Geoffrey Booth Date: Mon, 9 Nov 2026 15:54:03 -0800 Subject: [PATCH 2/4] modules: address review feedback on migration guide Document the ponyfill's cross-hook loading divergence, set an explicit `everysync` timeout in the example and explain the default, and show the `ERR_MODULE_REGISTER_REMOVED` error that `module.register()` now throws. Co-Authored-By: Claude Sonnet 5.5 --- pages/modules/migrating-from-module-register.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/pages/modules/migrating-from-module-register.md b/pages/modules/migrating-from-module-register.md index 7519bd3..6ba5a06 100644 --- a/pages/modules/migrating-from-module-register.md +++ b/pages/modules/migrating-from-module-register.md @@ -162,7 +162,7 @@ Two options keep the asynchronous work off your main thread. ### Keep your hooks module as it is -[`module-register-ponyfill`](https://github.com/joyeecheung/module-register-ponyfill) provides `register()` on top of `registerHooks()`, a worker thread and `Atomics`, so an existing hooks module works unchanged. Install it, then replace `import { register } from 'node:module'` with an import from the package: +[`module-register-ponyfill`](https://github.com/joyeecheung/module-register-ponyfill) provides `register()` on top of `registerHooks()`, a worker thread and `Atomics`, so an existing hooks module usually works unchanged. Install it, then replace `import { register } from 'node:module'` with an import from the package: ```js // register.mjs @@ -171,9 +171,11 @@ import { register } from 'module-register-ponyfill'; register('./hooks.mjs', import.meta.url); ``` +It doesn’t reproduce every detail of the native implementation; see its [known divergences](https://github.com/joyeecheung/module-register-ponyfill#known-divergences-from-native-moduleregister). The most likely to affect a migration: earlier `register()` calls no longer affect how later hooks modules are loaded. For example, registering a hook that enables TypeScript and then a `.ts` hooks module worked natively but won’t work with the ponyfill. If your hooks bootstrap each other this way, migrate those to `registerHooks()` instead. + ### Build a bridge with `everysync` -[`everysync`](https://github.com/mcollina/everysync) lets synchronous code call an asynchronous function that runs in a worker thread: the caller blocks until the worker’s promise settles. That is what a synchronous `load` hook needs to fetch modules from a URL, for example. +[`everysync`](https://github.com/mcollina/everysync) lets synchronous code call an asynchronous function that runs in a worker thread: the caller blocks until the worker’s promise settles or a timeout expires. That is what a synchronous `load` hook needs to fetch modules from a URL, for example. First, the worker exposes the asynchronous work: @@ -209,7 +211,8 @@ const worker = new Worker(new URL('./fetch-worker.mjs', import.meta.url), { execArgv: [], // Don't re-run this file (via --import) inside the worker. }); worker.unref(); // Don't let the worker keep the process alive. -const { fetchText } = makeSync(buffer); +// The default timeout is 1 second per call, so allow longer for the network. +const { fetchText } = makeSync(buffer, { timeout: 30_000 }); registerHooks({ resolve(specifier, context, nextResolve) { @@ -231,7 +234,7 @@ registerHooks({ node --import ./register.mjs app.mjs ``` -Two details matter. Pass `execArgv: []` when you preload the registration file with `--import`, because workers inherit your flags and would otherwise run `register.mjs` themselves and start another worker (`makeSync()` then fails with “The initialization timed out”). And remember that the calling thread is blocked while the worker waits on the network, so this suits tooling and development more than hot paths. +Two details matter. Pass `execArgv: []` when you preload the registration file with `--import`, because workers inherit your flags and would otherwise run `register.mjs` themselves and start another worker (`makeSync()` then fails with “The initialization timed out”). And remember that the calling thread is blocked while the worker waits on the network, so this suits tooling and development more than hot paths. `everysync` gives up after one second by default (`The response timed out after 1000ms`), so choose a `timeout` that suits your slowest request. ### Hooks now apply to `require()` too @@ -258,7 +261,7 @@ const { default: greeting } = await import('virtual:greeting'); ## Troubleshooting - `bad option: --loader` or `bad option: --experimental-loader`: see [Replacing `--loader`](#replacing---loader-and---experimental-loader). -- `SyntaxError: The requested module 'node:module' does not provide an export named 'register'`, or `module.register is not a function`: switch to `registerHooks()`, as described [above](#rewriting-your-hooks). +- `ERR_MODULE_REGISTER_REMOVED: module.register() has been removed (DEP0205)`: `module.register()` now throws. Switch to `registerHooks()`, as described [above](#rewriting-your-hooks). - A hook that worked before now fails with `Promise` or `await` errors: it is probably returning a promise from a synchronous hook. Remove `async`. For the full hook reference, including the `context` objects and every return value, see the [`module` API documentation](https://nodejs.org/api/module.html#customization-hooks). From c621a357645851a2f19e8b188b2bc84453b3ec0c Mon Sep 17 00:00:00 2001 From: Geoffrey Booth Date: Sat, 14 Nov 2026 14:56:34 -0800 Subject: [PATCH 3/4] modules: rewrite guide as evergreen customization hooks guide Restructure the page as a general guide to module customization hooks (synchronous work with registerHooks(), asynchronous work with module-register-ponyfill and everysync) instead of a migration guide, with a short end-of-life section for module.register(). The migration steps move to a userland-migrations recipe. Co-Authored-By: Claude Sonnet 5.5 --- .../modules/migrating-from-module-register.md | 267 --------------- pages/modules/using-customization-hooks.md | 319 ++++++++++++++++++ site.json | 4 +- 3 files changed, 321 insertions(+), 269 deletions(-) delete mode 100644 pages/modules/migrating-from-module-register.md create mode 100644 pages/modules/using-customization-hooks.md diff --git a/pages/modules/migrating-from-module-register.md b/pages/modules/migrating-from-module-register.md deleted file mode 100644 index 6ba5a06..0000000 --- a/pages/modules/migrating-from-module-register.md +++ /dev/null @@ -1,267 +0,0 @@ ---- -authors: GeoffreyBooth ---- - -# Migrating from `module.register()` to `module.registerHooks()` - -Node.js 27 removes `module.register()` and the `--experimental-loader` and `--loader` flags ([DEP0205](https://nodejs.org/api/deprecations.html#dep0205-moduleregister)). These provided _asynchronous_ module customization hooks, which ran on a separate loader thread. They were documented as experimental, deprecated in the docs in Node.js 24.15.0 and 25.9.0, and began printing a runtime warning in Node.js 26.0.0. - -[`module.registerHooks()`](https://nodejs.org/api/module.html#moduleregisterhooksoptions) is the replacement. It takes the same kinds of hooks (`resolve` and `load`), but they are synchronous and run on the thread that loads your modules. In most cases that makes them simpler to write and faster to run. - -## Pick your path - -| Your hooks… | Do this | -| ------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| can run synchronously on the main thread (most can) | Rewrite them for `registerHooks()`, as described [below](#rewriting-your-hooks). | -| depend on asynchronous work, and you can’t or don’t want to rewrite them | Use [`module-register-ponyfill`](https://github.com/joyeecheung/module-register-ponyfill), a drop-in `register()` built on `registerHooks()` and a worker thread. | -| need their own off-thread design | Build it on `registerHooks()` plus a worker; [`everysync`](https://github.com/mcollina/everysync) turns async worker APIs into synchronous calls. | - -`registerHooks()` is available in Node.js 22.15.0 and later (and 23.5.0 and later). If your package supports older versions, feature-detect it: - -```js -import module from 'node:module'; - -if (typeof module.registerHooks === 'function') { - module.registerHooks({ resolve, load }); -} else { - module.register('./hooks.mjs', import.meta.url); -} -``` - -## Rewriting your hooks - -An asynchronous hooks module, registered with `register()`: - -```js -// hooks.mjs -export async function resolve(specifier, context, nextResolve) { - if (specifier === 'virtual:greeting') { - return { url: 'virtual:greeting', shortCircuit: true }; - } - return nextResolve(specifier, context); -} - -export async function load(url, context, nextLoad) { - if (url === 'virtual:greeting') { - return { - format: 'module', - source: 'export default "hello"', - shortCircuit: true, - }; - } - return nextLoad(url, context); -} -``` - -```js -// register.mjs -import { register } from 'node:module'; - -register('./hooks.mjs', import.meta.url); -``` - -The same hooks, registered with `registerHooks()`: - -```js -// register.mjs -import { registerHooks } from 'node:module'; - -registerHooks({ - resolve(specifier, context, nextResolve) { - if (specifier === 'virtual:greeting') { - return { url: 'virtual:greeting', shortCircuit: true }; - } - return nextResolve(specifier, context); - }, - load(url, context, nextLoad) { - if (url === 'virtual:greeting') { - return { - format: 'module', - source: 'export default "hello"', - shortCircuit: true, - }; - } - return nextLoad(url, context); - }, -}); -``` - -The hook functions have the same names, arguments and return values. What changed: - -- Remove `async` and `await`. `nextResolve()` and `nextLoad()` return their results directly. -- Pass the hooks straight to `registerHooks()` instead of exporting them from a separate module, so there is no specifier or `parentURL` to resolve. You can still keep them in their own file and `import` them. - -Run your app with the registration file preloaded, the same way you did before: - -```bash -node --import ./register.mjs app.mjs -``` - -## Replacing `--loader` and `--experimental-loader` - -These flags took a module that exported hooks. Replace the flag with `--import` and a small file that registers them: - -```bash -# Before (removed) -node --experimental-loader ./hooks.mjs app.mjs - -# After -node --import ./register.mjs app.mjs -``` - -Running Node.js 27 with either flag fails with `bad option: --loader` (or `--experimental-loader`). - -## What behaves differently - -### Hooks run on the main thread - -Asynchronous hooks had their own thread and global scope, so they passed data through `initialize()`, the `data` option and message ports. Synchronous hooks share your application’s thread and globals, so none of that is needed. Use a closure or module-level state instead: - -```js -import { registerHooks } from 'node:module'; - -const prefix = '>> '; // was passed through `initialize({ prefix })` - -registerHooks({ - resolve(specifier, context, nextResolve) { - console.log(prefix + 'resolving', specifier); - return nextResolve(specifier, context); - }, -}); -``` - -There is no `initialize` hook, `data` option or `transferList` option. A slow hook now blocks your application instead of a background thread, so keep them fast. - -### Hooks can’t be asynchronous - -If a hook awaited something, such as a file read, replace it with a synchronous equivalent: - -```js -import { registerHooks } from 'node:module'; -import { readFileSync } from 'node:fs'; - -registerHooks({ - load(url, context, nextLoad) { - if (url.endsWith('.txt')) { - return { - format: 'module', - shortCircuit: true, - source: `export default ${JSON.stringify(readFileSync(new URL(url), 'utf8'))};`, - }; - } - return nextLoad(url, context); - }, -}); -``` - -If the work can’t be made synchronous (a network request, for example), see [Hooks that need asynchronous work](#hooks-that-need-asynchronous-work). - -## Hooks that need asynchronous work - -Two options keep the asynchronous work off your main thread. - -### Keep your hooks module as it is - -[`module-register-ponyfill`](https://github.com/joyeecheung/module-register-ponyfill) provides `register()` on top of `registerHooks()`, a worker thread and `Atomics`, so an existing hooks module usually works unchanged. Install it, then replace `import { register } from 'node:module'` with an import from the package: - -```js -// register.mjs -import { register } from 'module-register-ponyfill'; - -register('./hooks.mjs', import.meta.url); -``` - -It doesn’t reproduce every detail of the native implementation; see its [known divergences](https://github.com/joyeecheung/module-register-ponyfill#known-divergences-from-native-moduleregister). The most likely to affect a migration: earlier `register()` calls no longer affect how later hooks modules are loaded. For example, registering a hook that enables TypeScript and then a `.ts` hooks module worked natively but won’t work with the ponyfill. If your hooks bootstrap each other this way, migrate those to `registerHooks()` instead. - -### Build a bridge with `everysync` - -[`everysync`](https://github.com/mcollina/everysync) lets synchronous code call an asynchronous function that runs in a worker thread: the caller blocks until the worker’s promise settles or a timeout expires. That is what a synchronous `load` hook needs to fetch modules from a URL, for example. - -First, the worker exposes the asynchronous work: - -```js -// fetch-worker.mjs -import { wire } from 'everysync'; -import { workerData } from 'node:worker_threads'; - -wire(workerData.buffer, { - async fetchText(url) { - const response = await fetch(url); - return await response.text(); - }, -}); - -// Keep the worker's event loop alive. -setInterval(() => {}, 100000); -``` - -Then the registration file starts the worker and calls it from the hooks as if it were synchronous: - -```js -// register.mjs -import { registerHooks } from 'node:module'; -import { Worker } from 'node:worker_threads'; -import { makeSync } from 'everysync'; - -const buffer = new SharedArrayBuffer(1024, { - maxByteLength: 64 * 1024 * 1024, -}); -const worker = new Worker(new URL('./fetch-worker.mjs', import.meta.url), { - workerData: { buffer }, - execArgv: [], // Don't re-run this file (via --import) inside the worker. -}); -worker.unref(); // Don't let the worker keep the process alive. -// The default timeout is 1 second per call, so allow longer for the network. -const { fetchText } = makeSync(buffer, { timeout: 30_000 }); - -registerHooks({ - resolve(specifier, context, nextResolve) { - if (specifier.startsWith('https://')) { - return { url: specifier, shortCircuit: true }; - } - return nextResolve(specifier, context); - }, - load(url, context, nextLoad) { - if (url.startsWith('https://')) { - return { format: 'module', source: fetchText(url), shortCircuit: true }; - } - return nextLoad(url, context); - }, -}); -``` - -```bash -node --import ./register.mjs app.mjs -``` - -Two details matter. Pass `execArgv: []` when you preload the registration file with `--import`, because workers inherit your flags and would otherwise run `register.mjs` themselves and start another worker (`makeSync()` then fails with “The initialization timed out”). And remember that the calling thread is blocked while the worker waits on the network, so this suits tooling and development more than hot paths. `everysync` gives up after one second by default (`The response timed out after 1000ms`), so choose a `timeout` that suits your slowest request. - -### Hooks now apply to `require()` too - -Asynchronous hooks did not affect every `require()` call in a CommonJS module graph. Synchronous hooks run for `import`, `require()` and `createRequire()`, so a hook that previously only saw `import` will now also see CommonJS loads. If your hook assumes every module is ESM, check `context.format` or `context.conditions`. - -### Workers don’t inherit hooks - -Hooks registered with `registerHooks()` apply only to the thread that registered them. To use them in worker threads, either call `registerHooks()` in each worker, or register them in a file preloaded with `--import` (or `--require`); workers inherit those flags through `process.execArgv`: - -```bash -node --import ./register.mjs app.mjs -``` - -### Register before loading the modules you want to customize - -As before, hooks only affect modules loaded after they are registered. Preloading with `--import` guarantees this. If you register inside your application, load the customized modules afterward with a dynamic `import()`: - -```js -import './register.mjs'; - -const { default: greeting } = await import('virtual:greeting'); -``` - -## Troubleshooting - -- `bad option: --loader` or `bad option: --experimental-loader`: see [Replacing `--loader`](#replacing---loader-and---experimental-loader). -- `ERR_MODULE_REGISTER_REMOVED: module.register() has been removed (DEP0205)`: `module.register()` now throws. Switch to `registerHooks()`, as described [above](#rewriting-your-hooks). -- A hook that worked before now fails with `Promise` or `await` errors: it is probably returning a promise from a synchronous hook. Remove `async`. - -For the full hook reference, including the `context` objects and every return value, see the [`module` API documentation](https://nodejs.org/api/module.html#customization-hooks). diff --git a/pages/modules/using-customization-hooks.md b/pages/modules/using-customization-hooks.md new file mode 100644 index 0000000..ccba436 --- /dev/null +++ b/pages/modules/using-customization-hooks.md @@ -0,0 +1,319 @@ +--- +authors: GeoffreyBooth +--- + +# Using module customization hooks + +Module customization hooks let you change how Node.js resolves and loads modules, without touching the modules themselves. A `resolve` hook decides what a specifier such as `'./app'` or `'lodash'` points to, and a `load` hook decides what source code and format the resulting URL has. With them you can: + +- add support for file types Node.js doesn’t load natively, such as JSX, SVG, CoffeeScript or `.txt` files; +- serve virtual modules that don’t exist on disk; +- redirect or alias specifiers; +- mock modules in tests. + +Hooks are registered with [`module.registerHooks()`](https://nodejs.org/api/module.html#moduleregisterhooksoptions), which is available in Node.js 22.15.0 and later (and 23.5.0 and later). It takes synchronous hooks that run on the same thread that loads your modules. Some hooks need to wait on something asynchronous, like a network request; [that case is covered below](#asynchronous-work). + +For the full hook reference, including the `context` objects and every return value, see the [`module` API documentation](https://nodejs.org/api/module.html#customization-hooks). + +## Synchronous work + +### What is “synchronous work” + +A hook does synchronous work if it can compute its result and return it without waiting. Rewriting a specifier, matching a file extension, reading a file with `readFileSync()` and transforming source text with a synchronous compiler all qualify. Most hooks fall into this category. + +### How to do it with `module.registerHooks()` + +Pass `resolve` and/or `load` functions to `registerHooks()`. Each receives the usual arguments plus a `nextResolve()` or `nextLoad()` function that calls the next hook in the chain (or Node.js’s default behavior), and returns its result directly: + +```js +// register.js +import { registerHooks } from 'node:module'; +import { readFileSync } from 'node:fs'; + +registerHooks({ + load(url, context, nextLoad) { + if (url.endsWith('.txt')) { + const text = readFileSync(new URL(url), 'utf8'); + return { + format: 'module', + shortCircuit: true, + source: `export default ${JSON.stringify(text)};`, + }; + } + return nextLoad(url, context); + }, +}); +``` + +```js +// app.js +import greeting from './greeting.txt'; + +console.log(greeting); // The contents of greeting.txt +``` + +Run your app with the registration file preloaded, so that the hooks are in place before any of your modules load: + +```bash +node --import ./register.js app.js +``` + +A `resolve` hook works the same way: it receives `(specifier, context, nextResolve)`, and either returns its own `{ url, shortCircuit: true }` or calls `nextResolve()`. You can also put the hooks in their own file and `import` them into the registration file. + +Hooks can also run a compiler synchronously. This one makes `.jsx` files importable, using [esbuild](https://esbuild.github.io/)’s synchronous `transformSync()` to compile them: + +```js +// register.js +import { registerHooks } from 'node:module'; +import { readFileSync } from 'node:fs'; +import { transformSync } from 'esbuild'; + +registerHooks({ + load(url, context, nextLoad) { + if (url.endsWith('.jsx')) { + const source = readFileSync(new URL(url), 'utf8'); + const { code } = transformSync(source, { + loader: 'jsx', + jsx: 'automatic', + format: 'esm', + sourcefile: new URL(url).pathname, + }); + return { format: 'module', shortCircuit: true, source: code }; + } + return nextLoad(url, context); + }, +}); +``` + +```jsx +// Greeting.jsx +export function Greeting({ name }) { + return

Hello, {name}!

; +} +``` + +```jsx +// app.jsx +import { renderToStaticMarkup } from 'react-dom/server'; +import { Greeting } from './Greeting.jsx'; + +console.log(renderToStaticMarkup()); //

Hello, world!

+``` + +```bash +node --import ./register.js app.jsx +``` + +The same approach works for any language that compiles to JavaScript. For example, a hook for CoffeeScript, using the [`coffeescript`](https://coffeescript.org/) package: + +```js +// register.js +import { registerHooks } from 'node:module'; +import { readFileSync } from 'node:fs'; +import CoffeeScript from 'coffeescript'; + +registerHooks({ + load(url, context, nextLoad) { + if (url.endsWith('.coffee')) { + const source = readFileSync(new URL(url), 'utf8'); + return { + format: 'module', + shortCircuit: true, + source: CoffeeScript.compile(source, { bare: true }), + }; + } + return nextLoad(url, context); + }, +}); +``` + +```coffee +# greet.coffee +export greet = (name) -> "Hello, #{name}!" +``` + +```js +// app.js +import { greet } from './greet.coffee'; + +console.log(greet('world')); // Hello, world! +``` + +Because hooks run on your application’s thread, they share its globals, so state can live in a closure or a module-level variable: + +```js +import { registerHooks } from 'node:module'; + +const prefix = '>> '; + +registerHooks({ + resolve(specifier, context, nextResolve) { + console.log(prefix + 'resolving', specifier); + return nextResolve(specifier, context); + }, +}); +``` + +A slow hook blocks your application, so keep them fast. + +For a collection of robust, ready-made hooks and more examples, see [`@nodejs-loaders`](https://github.com/nodejs-loaders/nodejs-loaders). + +### Things to keep in mind + +#### Hooks apply to `require()` too + +Hooks run for `import`, `require()` and `createRequire()`, so they see CommonJS modules as well as ES modules. If your hook assumes every module is ESM, check `context.format` or `context.conditions`. + +#### Workers don’t inherit hooks + +Hooks registered with `registerHooks()` apply only to the thread that registered them. To use them in worker threads, either call `registerHooks()` in each worker, or register them in a file preloaded with `--import` (or `--require`); workers inherit those flags through `process.execArgv`: + +```bash +node --import ./register.js app.js +``` + +#### Register before loading the modules you want to customize + +Hooks only affect modules loaded after they are registered. Preloading with `--import` guarantees this. If you register inside your application, load the customized modules afterward with a dynamic `import()`: + +```js +import './register.js'; + +const { default: greeting } = await import('./greeting.txt'); +``` + +## Asynchronous work + +### What is “asynchronous work” + +A hook does asynchronous work if it has to wait for something before it can return, such as a network request or a call into a library that only offers a promise-based API. `registerHooks()` can’t wait on a promise: its hooks must return their results directly. There are two ways to get that work done anyway, both of which run it off your main thread. + +### Write asynchronous hooks with `module-register-ponyfill` + +[`module-register-ponyfill`](https://github.com/joyeecheung/module-register-ponyfill) lets you write hooks as a module whose `resolve` and `load` functions are `async`. Its `register()` function runs that module on a worker thread, and uses `registerHooks()` and `Atomics` to make the results available to the loader synchronously. Install it with `npm install module-register-ponyfill`, then write the hooks module: + +```js +// hooks.js +export async function resolve(specifier, context, nextResolve) { + if (specifier.startsWith('https://')) { + return { url: specifier, shortCircuit: true }; + } + return nextResolve(specifier, context); +} + +export async function load(url, context, nextLoad) { + if (url.startsWith('https://')) { + const response = await fetch(url); + return { + format: 'module', + source: await response.text(), + shortCircuit: true, + }; + } + return nextLoad(url, context); +} +``` + +And register it: + +```js +// register.js +import { register } from 'module-register-ponyfill'; + +register('./hooks.js', import.meta.url); +``` + +```bash +node --import ./register.js app.js +``` + +Now `app.js` can `import` a module from an `https://` URL. The hooks module runs on its own thread, so it has its own global scope and doesn’t share state with your application. + +The ponyfill has a few limitations; see its [known divergences](https://github.com/joyeecheung/module-register-ponyfill#known-divergences-from-native-moduleregister). For example, hooks registered by one `register()` call don’t affect how later hooks modules are loaded, so a hook that enables JSX won’t let you write the next hooks module in JSX. + +### Build a bridge with `everysync` + +[`everysync`](https://github.com/mcollina/everysync) lets synchronous code call an asynchronous function that runs in a worker thread: the caller blocks until the worker’s promise settles or a timeout expires. That is what a synchronous `load` hook needs to fetch modules from a URL, for example. + +First, the worker exposes the asynchronous work: + +```js +// fetch-worker.js +import { wire } from 'everysync'; +import { workerData } from 'node:worker_threads'; + +wire(workerData.buffer, { + async fetchText(url) { + const response = await fetch(url); + return await response.text(); + }, +}); + +// Keep the worker's event loop alive. +setInterval(() => {}, 100000); +``` + +Then the registration file starts the worker and calls it from the hooks as if it were synchronous: + +```js +// register.js +import { registerHooks } from 'node:module'; +import { Worker } from 'node:worker_threads'; +import { makeSync } from 'everysync'; + +const buffer = new SharedArrayBuffer(1024, { + maxByteLength: 64 * 1024 * 1024, +}); +const worker = new Worker(new URL('./fetch-worker.js', import.meta.url), { + workerData: { buffer }, + execArgv: [], // Don't re-run this file (via --import) inside the worker. +}); +worker.unref(); // Don't let the worker keep the process alive. +// The default timeout is 1 second per call, so allow longer for the network. +const { fetchText } = makeSync(buffer, { timeout: 30_000 }); + +registerHooks({ + resolve(specifier, context, nextResolve) { + if (specifier.startsWith('https://')) { + return { url: specifier, shortCircuit: true }; + } + return nextResolve(specifier, context); + }, + load(url, context, nextLoad) { + if (url.startsWith('https://')) { + return { format: 'module', source: fetchText(url), shortCircuit: true }; + } + return nextLoad(url, context); + }, +}); +``` + +```bash +node --import ./register.js app.js +``` + +Two details matter. Pass `execArgv: []` when you preload the registration file with `--import`, because workers inherit your flags and would otherwise run `register.js` themselves and start another worker (`makeSync()` then fails with “The initialization timed out”). And remember that the calling thread is blocked while the worker waits on the network, so this suits tooling and development more than hot paths. `everysync` gives up after one second by default (`The response timed out after 1000ms`), so choose a `timeout` that suits your slowest request. + +## End of life for `module.register()` + +Earlier versions of Node.js had another way to register hooks: `module.register()`, along with the `--experimental-loader` and `--loader` flags. Those ran asynchronous hooks on a separate loader thread. Node.js 27 removes them ([DEP0205](https://nodejs.org/api/deprecations.html#dep0205-moduleregister)); they were deprecated in the documentation in Node.js 24.15.0 and 25.9.0, and began printing a runtime warning in Node.js 26.0.0. + +If you have code that still uses them, the [`module-register-to-register-hooks`](https://github.com/nodejs/userland-migrations) codemod, one of the [userland migrations](/learn/getting-started/userland-migrations), rewrites the common cases for you. Hooks that do asynchronous work can use the approaches in [Asynchronous work](#asynchronous-work) instead. + +If your package has to support versions of Node.js with and without `registerHooks()`, feature-detect it. Check for `registerHooks()` first, then for `module.register()` (which only exists in older versions), and handle versions that have neither: + +```js +import module from 'node:module'; + +if (typeof module.registerHooks === 'function') { + module.registerHooks({ resolve, load }); +} else if (typeof module.register === 'function') { + module.register('./hooks.js', import.meta.url); +} else { + // This version of Node.js doesn't support customization hooks at all. + // Skip them, as here, or throw an error if your package can't work without them. + console.warn( + 'Module customization hooks are not supported by this version of Node.js.' + ); +} +``` diff --git a/site.json b/site.json index f880183..9c615c5 100644 --- a/site.json +++ b/site.json @@ -353,8 +353,8 @@ "label": "ABI Stability" }, { - "link": "/learn/modules/migrating-from-module-register", - "label": "Migrating from module.register()" + "link": "/learn/modules/using-customization-hooks", + "label": "Using module customization hooks" } ] }, From 1de321c0823a1db798185b132e93694429aa730d Mon Sep 17 00:00:00 2001 From: Geoffrey Booth Date: Sun, 15 Nov 2026 08:38:22 -0800 Subject: [PATCH 4/4] modules: address review feedback on customization hooks guide Use a `?raw` query import for the first example instead of `.txt`, note that matching on file extension isn't robust, drop the 23.5.0 version mention, reword the sync and async intros, add a caution about deadlocks, point to @nodejs-loaders from the feature-detection snippet, and use `sh` for shell code fences. Co-Authored-By: Claude Sonnet 5.5 --- pages/modules/using-customization-hooks.md | 38 +++++++++++++--------- 1 file changed, 22 insertions(+), 16 deletions(-) diff --git a/pages/modules/using-customization-hooks.md b/pages/modules/using-customization-hooks.md index ccba436..c7b12ff 100644 --- a/pages/modules/using-customization-hooks.md +++ b/pages/modules/using-customization-hooks.md @@ -6,12 +6,12 @@ authors: GeoffreyBooth Module customization hooks let you change how Node.js resolves and loads modules, without touching the modules themselves. A `resolve` hook decides what a specifier such as `'./app'` or `'lodash'` points to, and a `load` hook decides what source code and format the resulting URL has. With them you can: -- add support for file types Node.js doesn’t load natively, such as JSX, SVG, CoffeeScript or `.txt` files; -- serve virtual modules that don’t exist on disk; -- redirect or alias specifiers; -- mock modules in tests. +- add support for file types Node.js doesn’t load natively, such as JSX, SVG or CoffeeScript +- serve virtual modules that don’t exist on disk +- redirect or alias specifiers +- mock modules in tests -Hooks are registered with [`module.registerHooks()`](https://nodejs.org/api/module.html#moduleregisterhooksoptions), which is available in Node.js 22.15.0 and later (and 23.5.0 and later). It takes synchronous hooks that run on the same thread that loads your modules. Some hooks need to wait on something asynchronous, like a network request; [that case is covered below](#asynchronous-work). +Hooks are registered with [`module.registerHooks()`](https://nodejs.org/api/module.html#moduleregisterhooksoptions), which is available in Node.js 22.15.0 and later. It takes synchronous hooks that run on the same thread as your modules. Some hooks need to wait on something asynchronous, like a network request; [that case is covered below](#asynchronous-work). For the full hook reference, including the `context` objects and every return value, see the [`module` API documentation](https://nodejs.org/api/module.html#customization-hooks). @@ -19,7 +19,7 @@ For the full hook reference, including the `context` objects and every return va ### What is “synchronous work” -A hook does synchronous work if it can compute its result and return it without waiting. Rewriting a specifier, matching a file extension, reading a file with `readFileSync()` and transforming source text with a synchronous compiler all qualify. Most hooks fall into this category. +Most hooks work falls into this category. Perhaps best described by what it isn’t: no async/await, no promises, no postMessage, etc. Rewriting a specifier, matching a file extension, reading a file with `readFileSync()` and transforming source text with a synchronous compiler all qualify. ### How to do it with `module.registerHooks()` @@ -32,7 +32,7 @@ import { readFileSync } from 'node:fs'; registerHooks({ load(url, context, nextLoad) { - if (url.endsWith('.txt')) { + if (new URL(url).searchParams.has('raw')) { const text = readFileSync(new URL(url), 'utf8'); return { format: 'module', @@ -47,19 +47,23 @@ registerHooks({ ```js // app.js -import greeting from './greeting.txt'; +import greeting from './greeting.txt?raw'; console.log(greeting); // The contents of greeting.txt ``` +This hook makes any import that ends in `?raw` return the file’s contents as a string, a convention borrowed from [Vite](https://vite.dev/guide/assets#importing-asset-as-string). It works for any file type, so `./styles.css?raw` would work too. + Run your app with the registration file preloaded, so that the hooks are in place before any of your modules load: -```bash +```sh node --import ./register.js app.js ``` A `resolve` hook works the same way: it receives `(specifier, context, nextResolve)`, and either returns its own `{ url, shortCircuit: true }` or calls `nextResolve()`. You can also put the hooks in their own file and `import` them into the registration file. +The examples below match files with `url.endsWith('.jsx')` or similar to keep them short, but that isn’t robust enough for real use: hooks often pass information along in a query string, which comes after the file extension (`Greeting.jsx?v=2`), so a check like `endsWith('.jsx')` would miss it. Parse the URL, as the hook above does, and check its `pathname` instead. + Hooks can also run a compiler synchronously. This one makes `.jsx` files importable, using [esbuild](https://esbuild.github.io/)’s synchronous `transformSync()` to compile them: ```js @@ -100,7 +104,7 @@ import { Greeting } from './Greeting.jsx'; console.log(renderToStaticMarkup()); //

Hello, world!

``` -```bash +```sh node --import ./register.js app.jsx ``` @@ -168,7 +172,7 @@ Hooks run for `import`, `require()` and `createRequire()`, so they see CommonJS Hooks registered with `registerHooks()` apply only to the thread that registered them. To use them in worker threads, either call `registerHooks()` in each worker, or register them in a file preloaded with `--import` (or `--require`); workers inherit those flags through `process.execArgv`: -```bash +```sh node --import ./register.js app.js ``` @@ -179,14 +183,16 @@ Hooks only affect modules loaded after they are registered. Preloading with `--i ```js import './register.js'; -const { default: greeting } = await import('./greeting.txt'); +const { default: greeting } = await import('./greeting.txt?raw'); ``` ## Asynchronous work ### What is “asynchronous work” -A hook does asynchronous work if it has to wait for something before it can return, such as a network request or a call into a library that only offers a promise-based API. `registerHooks()` can’t wait on a promise: its hooks must return their results directly. There are two ways to get that work done anyway, both of which run it off your main thread. +This tends to be more edge-case. A hook does asynchronous work if it has to wait for something before it can return, such as a network request or a call into a library that runs concurrently (exposing that via promise-based APIs). `registerHooks()` can’t wait on a promise—its hooks must return their results directly. There are two ways to get that work done anyway, both of which run it off your main thread. + +Be aware that this can get complicated. Making asynchronous work look synchronous means blocking the thread that loads your modules until another thread responds, so a worker that ends up waiting on the blocked thread (directly or indirectly) causes a deadlock, and a worker that never settles hangs your application. These problems, along with livelocks, can be hard to diagnose. If you can do the work synchronously, prefer that. ### Write asynchronous hooks with `module-register-ponyfill` @@ -223,7 +229,7 @@ import { register } from 'module-register-ponyfill'; register('./hooks.js', import.meta.url); ``` -```bash +```sh node --import ./register.js app.js ``` @@ -288,7 +294,7 @@ registerHooks({ }); ``` -```bash +```sh node --import ./register.js app.js ``` @@ -300,7 +306,7 @@ Earlier versions of Node.js had another way to register hooks: `module.register( If you have code that still uses them, the [`module-register-to-register-hooks`](https://github.com/nodejs/userland-migrations) codemod, one of the [userland migrations](/learn/getting-started/userland-migrations), rewrites the common cases for you. Hooks that do asynchronous work can use the approaches in [Asynchronous work](#asynchronous-work) instead. -If your package has to support versions of Node.js with and without `registerHooks()`, feature-detect it. Check for `registerHooks()` first, then for `module.register()` (which only exists in older versions), and handle versions that have neither: +If your package has to support versions of Node.js with and without `registerHooks()`, feature-detect it. The snippet below is a simplified sketch: a robust implementation also has to detect whether the hook chain is synchronous or asynchronous, which [`@nodejs-loaders`](https://github.com/nodejs-loaders/nodejs-loaders) handles for you. Check for `registerHooks()` first, then for `module.register()` (which only exists in older versions), and handle versions that have neither: ```js import module from 'node:module';