skip to content

Why does a Node.js script that logs process.nextTick output before promise callbacks as a .cjs file log it after them as .mjs?

level: seniorimportance: nice to knowfreq 25%

answer

  1. how the entry module is evaluated
  2. already inside a microtask drain
  3. top level only, not later callbacks
  4. syntax detection flips it too

basics

~20 s

An ES module is evaluated while Node is already draining V8's microtask queue, so promise callbacks queued at its top level run before Node returns to its next tick queue. Later timer and I/O callbacks keep the CommonJS order.

solid answer

~50 s

In CommonJS, Node runs the main script, then drains its own next tick queue before V8's microtask queue, so `process.nextTick` wins. An ES module entry is evaluated as part of microtask processing: the Node 24 docs say ES modules are processed already as part of the microtask queue. Promise reactions and `queueMicrotask()` callbacks scheduled at the module's top level join the drain that is already running, and Node reaches its tick queue only after it empties. The flip is limited to module evaluation, including code after a top-level `await`; inside a later `setTimeout`, `setImmediate` or I/O callback the tick runs first again. Since syntax detection became the default in Node 22.7.0, a typeless `.js` file that gains an `import` flips too. The fix is to stop relying on cross-queue order: chain the dependency or use one queue.

code

javascript · 11 lines
javascript
// order.mjs
import { nextTick } from 'node:process';

Promise.resolve().then(() => console.log('promise'));
queueMicrotask(() => console.log('microtask'));
nextTick(() => console.log('nextTick'));

setTimeout(() => {
  Promise.resolve().then(() => console.log('promise in timer'));
  nextTick(() => console.log('nextTick in timer'));
}, 0);

go deeper

for a junior

Remember that the same snippet can print in a different order depending on whether Node loads it as CommonJS or as an ES module.

for a middle

Explain the mechanism: module evaluation runs inside a microtask drain, so new microtasks run before Node returns to its next tick queue.

for a senior

Diagnose a migration regression by scoping the flip to module evaluation, checking how Node decided the file's format, and removing the hidden ordering dependency.

for a principal

Set a rule for an ESM migration: no code or test may depend on which deferral queue drains first, so format changes stay behaviour-neutral.

## The symptom A team converts a service, or just one test file, from CommonJS to ES modules. A test that asserted log order, or code that quietly relied on a `process.nextTick()` callback running before a promise callback, starts failing. Nothing else changed: same Node 24 binary, same code apart from `require` becoming `import`. The same three lines print in a different order: | Entry format | `Promise.resolve().then(A)`; `queueMicrotask(B)`; `process.nextTick(C)` prints | |---|---| | CommonJS (`.cjs`, or `.js` treated as CommonJS) | C, A, B | | ES module (`.mjs`, or `.js` treated as ES module) | A, B, C | ## Why the order flips Node keeps two queues: its own **next tick queue** (filled by `process.nextTick()`) and V8's **microtask queue** (promise reactions and `queueMicrotask()`). Its normal routine after an operation is: drain the tick queue, then drain the microtask queue, and repeat while ticks keep appearing. That routine assumes the operation ran *outside* any microtask drain, which is true for a CommonJS main script: Node calls into the script, the script returns, and Node starts draining with the tick queue. An **ES module is evaluated differently**. Node loads and evaluates ES modules through promise-based machinery, and its documentation states the consequence directly: ES modules are processed already as part of the microtask queue. When the module body schedules a promise reaction or a `queueMicrotask()` callback, V8 is still in the middle of draining microtasks, so it runs those new microtasks as part of the same drain. Node gets back to its next tick queue only after the microtask queue is empty. Hence `A, B, C`. ## Where the difference applies, and where it does not The reversal is narrower than "ESM runs microtasks first": - **It applies to code running during module evaluation**: the top level of the entry module, and code that runs after a top-level `await` resumes, because that continuation is itself a promise job. - **It does not apply to callbacks the loop invokes later.** Inside a `setTimeout()`, `setImmediate()` or I/O callback in an ES module, Node is back to its normal drain, and a `process.nextTick()` callback runs before a promise callback, exactly as in CommonJS. - **It is documented behaviour, not a bug.** The Node 24 documentation describes it in the `process.nextTick()` section ("When to use `queueMicrotask()` vs. `process.nextTick()`"). ## What decides whether a file is an ES module Because the order depends on the format, it matters which files Node treats as ES modules. In Node 24: 1. a file with the `.mjs` extension; 2. a `.js` file whose nearest `package.json` has `"type": "module"`; 3. string input run with `--input-type=module`; 4. an ambiguous `.js` file (no `type` field) that contains ES module syntax such as `import` or `export`. **Syntax detection** has been on by default since v22.7.0, so changing `require()` to `import` in a typeless package is enough to flip the order, without renaming anything. When such a file sits under a `package.json` that lacks a `type` field (outside `node_modules`), Node also prints a `MODULE_TYPELESS_PACKAGE_JSON` warning as it reparses the file. To confirm which format Node actually used for a file, log `typeof require` at its top level: it is `'function'` in CommonJS and `'undefined'` in an ES module, where `import.meta` is available instead. That one check settles most "it only broke after the migration" reports in seconds. ## Fixing the code rather than the format The real defect is depending on cross-queue order at all. - **Chain real dependencies.** If B needs A's result, put B in A's `.then` or after an `await`, not in a queue that happens to drain later. - **Use one queue.** `queueMicrotask()` and promise reactions share V8's queue and keep first-in, first-out order in both module formats; Node's docs recommend `queueMicrotask()` over `process.nextTick()` for most userland code. - **Keep `process.nextTick()` for its documented jobs**, such as emitting an event after a constructor returns, where the guarantee you need is "after the caller's synchronous code", not "before every promise job". - **Write order-sensitive tests against observable behaviour**, not against which internal queue ran first. ```js // fragile in either format: B assumes A already ran process.nextTick(() => state.ready = true); // A Promise.resolve().then(() => assert(state.ready)); // B // robust: the dependency is explicit Promise.resolve() .then(() => { state.ready = true; }) .then(() => assert(state.ready)); ```

  • Does code after a top-level await in an ES module get CommonJS ordering back?
    No. The continuation after a top-level `await` is itself a promise job, so it still runs inside a microtask drain; promise callbacks it schedules run before tick callbacks it schedules. The CommonJS order returns only in callbacks the event loop invokes later, such as timers, immediates and I/O completions.
  • A package has no type field and a developer swaps require() for import in index.js; why can ordering change without a rename?
    In Node 24 a typeless `.js` file containing ES module syntax is treated as an ES module through syntax detection, on by default since v22.7.0. The file is now evaluated as an ES module, so top-level ordering flips. Node prints a `MODULE_TYPELESS_PACKAGE_JSON` warning; adding an explicit `"type"` field removes the ambiguity.

  • In ES modules, process.nextTick callbacks always run after promise callbacks, even in timers.
  • The .mjs ordering change is a Node bug that an upgrade will fix.
  • Only a top-level await makes an ES module change the ordering.
  • Renaming the file is the only way a module's format changes.
  • Tests can rely on nextTick-versus-promise order as long as nobody changes the code.

Assumes Node.js 24: the ESM ordering itself is not tied to a release change, while syntax detection, which turns a typeless .js file with import syntax into an ES module, became the default in v22.7.0.