Repository navigation
modules: add guide to using module customization hooks - #190
GeoffreyBooth wants to merge 4 commits into
Conversation
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 <noreply@anthropic.com>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
👋 Codeowner Review RequestThe following codeowners have been identified for the changed files: Team reviewers: @nodejs/loaders @nodejs/nodejs-website Please review the changes when you have a chance. Thank you! 🙏 |
|
Should this be a learn article or a blog cc @nodejs/nodejs-website |
There was a problem hiding this comment.
🟡 Changes recommended
The migration guide overstates registration-chain compatibility and omits an explicit network-appropriate timeout, so valid hook bootstrapping or module downloads can fail.
2 open issues
What changed in this PR
Adds a migration guide to the Node.js learning documentation for the removal of module.register() and loader flags in Node.js 27.
Changes:
- Explains migration to
registerHooks()with before-and-after examples and behavioral differences. - Covers asynchronous alternatives, worker setup, and troubleshooting.
- Links the guide from the Modules navigation.
| File | Description |
|---|---|
site.json |
Adds the migration guide to the Modules navigation. |
pages/modules/migrating-from-module-register.md |
Documents migration paths, examples, compatibility considerations, and common errors. |
Review effort: Balanced
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 <noreply@anthropic.com>
Perhaps both? This page is meant to be the durable how-to, which is why I put it in Learn: it shows how to migrate, with working examples, and it will stay useful as people upgrade over time. A blog post can announce when nodejs/node#67090 lands and point people to this article. |
ovflowd
left a comment
There was a problem hiding this comment.
I'm unsure now what's the precedence. Where do migration guides usually go cc @JakobJingleheimer?
|
Thanks @GeoffreyBooth (and @ovflowd for the ping)! This wasn't quite what I had in mind: The existing Learn migration guides are long-lived type things, helping users adopt a node feature instead of a userland (npm) library/package that will likely continue to exist. Whereas this is a node deprecation migration (so it has an end-date). Individual userland-migrations cover themselves (and then are linked via the Intro to Userland Migrations Learn article). What I had envisioned was a more general-purpose guide, like: Using customisation hooksHow/why it's useful Synchronous workWhat is "synchronous work"How to do with
|
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 <noreply@anthropic.com>
|
Okay @JakobJingleheimer, I’ve restructured the page to match your outline: it’s now an evergreen “Using module customization hooks” guide, with sections on synchronous work ( The migration itself is now a codemod recipe in nodejs/userland-migrations#572, so the Intro to Userland Migrations article can link to it. Once it’s published on Learn, I’ll point the end-of-life section there instead of the repo. |
JakobJingleheimer
left a comment
There was a problem hiding this comment.
Thanks for the update! Looks pretty good to me; a few small things.
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 <noreply@anthropic.com>
|
@nodejs/nodejs-website Any notes? |
|
|
||
| ### What is “synchronous work” | ||
|
|
||
| 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. |
There was a problem hiding this comment.
I think this is a bit more complicated than necessary for beginners. The essential thing here is that the hook functions need to know the customized result by the time it returns synchronously. This doesn't necessarily always mean promises are out of scope (you could argue that you can return a synchronously resolved promise, which is the primitive that the spec actually uses to carry the result of synchronous evaluation of modules). But obviously it means if you can only get your result in a callback, you won't be able to return it synchronously in the hook function. In this case, you can consider doing that work in a different thread and block on it in the main thread to get the result and return synchronously in the main thread. I think it would be more straightforward to explain it by examples. e.g.
// load hook is interpreted to be a synchronous function and must return an object.
function load(url, context, nextLoad) {
const source = fs.readFileSync(new URL(url), 'utf8');
// Know the result already by the time it returns.
return { format: 'module', shortCircuit: true, source };
}
function load(url, context, nextLoad) {
fs.readFile(new URL(url), 'utf8', (err, data) => {
// result is only available in the callback
});
// We do not know the result yet by the time it returns.
// Try doing the work in a different thread, block on it, unwrap the result synchronously
// to return the result synchronously in the thread that's loading the module.
}
function load(url, context, nextLoad) {
fs.promises.readFile(new URL(url), 'utf8').then((data) => {
// result is only available in the callback
});
// We do not know the result yet by the time it returns.
// Try doing the work in a different thread, block on it, unwrap the result synchronously
// to return the result synchronously in the thread that's loading the module.
}|
|
||
| ### Things to keep in mind | ||
|
|
||
| #### Hooks apply to `require()` too |
There was a problem hiding this comment.
This seems unnecessary, only people who experienced the lack of support of require() needed to know that it works now, but it would be confusing to emphasize something that's already supposed to be working is working for anyone new to this .
|
|
||
| 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. |
There was a problem hiding this comment.
This sounds a bit fear mongering, it's better to spell out exactly when this can get dangerous. In general doing it synchronously is preferred is because it's just simpler and there's no overhead from inter-thread communication. There's generally no need to make things more complicated than it needs to be.
|
|
||
| ### What is “asynchronous work” | ||
|
|
||
| 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. |
There was a problem hiding this comment.
I think we should start with a straightforward example using worker + Atomics.await. You don't have to use any library for this since the idea is very straightforward anyway.
function getSource(url) {
const response = fetch(url); // But fetch is asynchronous?
const text = response.text(); // But response.text() is asynchronous?
return text;
}
function load(url, context, nextLoad) {
return { source: getSource(url), shortCircuit: true, format: 'module' }
}const {
Worker, MessageChannel, receiveMessageOnPort
} = require('node:worker_threads');
// Fetch the source remotely on a different thread, block on it until it returns.
function getSource(url) {
const { port1, port2 } = new MessageChannel();
const notifyHandle = new Int32Array(new SharedArrayBuffer(4));
const worker = new Worker(`
const { workerData } = require('node:worker_threads');
const { notifyHandle, port2 } = workerData;
(async () => {
const response = await fetch('${url}');
const text = await response.text();
port2.postMessage({ text });
Atomics.store(notifyHandle, 0, 1);
Atomics.notify(notifyHandle, 0);
})();
`, {
eval: true,
workerData: { notifyHandle, port2 },
transferList: [port2]
});
// Block until the worker finishes.
Atomics.wait(notifyHandle, 0, 0);
// Retrieve the result synchronously.
const { text } = receiveMessageOnPort(port1).message;
return text;
}
function load(url, context, nextLoad) {
return { source: getSource(url), shortCircuit: true, format: 'module' }
}Of course for a long-running hook you want to reuse the worker instead of keep spinning one for each request, this is just to show how it's supposed to work.


Adds a Learn guide to module customization hooks, written for someone using them for the first time. It lives at
/learn/modules/using-customization-hooksand is linked from the "Modules" group insite.json.This replaces the migration guide this PR originally added. Following review feedback, the page is an evergreen guide, not a migration guide for a deprecation with an end date. The migration lives in a userland-migrations recipe instead: nodejs/userland-migrations#572.
The page covers:
module.registerHooks(): a.txtloader, JSX (esbuild) and CoffeeScript compilers, and notes onrequire(), workers and registration order, with a pointer to@nodejs-loadersmodule-register-ponyfillor a bridge built witheverysyncmodule.register()and the--loaderflags (DEP0205, removed in module: remove async module customization hooks node#67090), with a link to the codemod and a feature-detection snippet for packages that support versions with and withoutregisterHooks()Once the recipe is published on Learn, the codemod link should point to
/learn/userland-migrations/module-register-to-register-hooks; for now it points to the repository.I ran every code example on the page on Node.js 26.12.1 (the network examples against a local HTTPS server).
🤖 Generated with Claude Code