Skip to content

fix(build): add experimental flag to rewrite leaked runtime require of bundled deps (#4171) - #4365

Closed
pi0x wants to merge 2 commits into
mainfrom
fix/ext-react
Closed

pi0x wants to merge 2 commits into
mainfrom
fix/ext-react

Conversation

@pi0x

@pi0x pi0x commented Jun 21, 2026 •

Copy link
Copy Markdown
Contributor

[ai assited] resolves #4171 via a workaround until upstream issue is fixed

Try:

  • Use "nitro": "https://pkg.pr.new/nitro@4365" in package.json
  • Inside nitro.config.ts add experimental: { cjsRequireRewrite: "react" }

Vite's SSR build lowers a require("react") inside vendored CommonJS (e.g. use-sync-external-store's shim, as shipped inside base-ui / recharts / reactflow) to a runtime __require("react") (createRequire), because React is an SSR-external. Once Nitro bundles React for a self-contained .output/, that require is left dangling:

  • Cannot find module 'react' when node_modules isn't shipped (Docker runner, serverless), or
  • Invalid hook call / null dispatcher when it is — __require loads a second React instance.

Root cause is the Vite SSR lowering (pure Rolldown links the same nested require correctly); this is a downstream workaround.

This PR adds an opt-in experimental.cjsRequireRewrite flag — a generateBundle pass that rewrites leaked __require("x") to the copy of x already bundled in the output, so a single instance is used and the output stays self-contained.

  • "react" — targets the React family (react, react-dom, react/jsx-runtime, …).
  • true — covers any bundled dependency that leaked a runtime require.
  • unset (default) — disabled, no behavior change.

Unresolved leaks emit a warning instead of shipping silently.

Vite's SSR build lowers a `require("react")` inside vendored CommonJS to a
runtime `__require("react")` (createRequire) because React is an SSR-external.
Once Nitro bundles React for a self-contained `.output/`, that require is left
dangling: it fails with `Cannot find module 'react'` when node_modules is not
shipped, or loads a duplicate React instance ("Invalid hook call") when it is.

Add an opt-in `experimental.cjsRequireRewrite` flag that rewrites such leaked
requires to the copy already bundled in the output. `"react"` targets the React
family; `true` covers any bundled dependency. Unresolved leaks warn instead of
shipping silently.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@pi0x
pi0x requested a review from pi0 as a code owner June 21, 2026 09:12
@vercel

vercel Bot commented Jun 21, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
nitro.build Ready Ready Preview Oct 13, 2026 1:39pm UTC

Request Review

@coderabbitai

coderabbitai Bot commented Jun 21, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
📝 Walkthrough

A new nitro:cjs-require Rollup/Nitro build plugin is added to rewrite leaked runtime __require("specifier") calls in bundled SSR output chunks. The feature is gated by a new experimental.cjsRequireRewrite option (boolean | "react") in NitroOptions, wired conditionally into baseBuildPlugins, and covered by a unit test suite.

Changes

CJS require rewrite plugin

Layer / File(s) Summary
Config option and plugin registration
src/types/config.ts, src/build/plugins.ts
Adds experimental.cjsRequireRewrite?: boolean | "react" to NitroOptions, imports the new plugin, and conditionally registers cjsRequire(nitro, mode) in baseBuildPlugins with mode set to "all" for true or "react" otherwise.
Plugin core: chunk scanning, initializer resolution, and rewriting
src/build/plugins/cjs-require.ts
Defines CjsRequireMode, React-mode initializer constants, and the full generateBundle hook: scans all output chunks for __require("…") call sites and CJS initializer definitions, resolves an initializer per leaked specifier, injects missing export { initVar as alias } into provider chunks, rewrites consumer chunks to call the initializer (prepending cross-chunk imports when needed), and warns on unresolvable bundled specifiers. Includes helpers for initializer name derivation, package extraction, bundled-package detection, export-alias parsing, relative import path, shebang-safe prepend, and regex escaping.
Unit tests
test/unit/cjs-require.test.ts
Tests rewrite and warning behavior across default, "react", and "all" modes, including export injection, external require passthrough, missing-initializer warnings, and no-op on clean bundles.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 15.38% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The PR successfully addresses issue #4171 by implementing the cjsRequireRewrite mechanism to rewrite leaked __require() calls for bundled dependencies, resolving the 'Cannot find module react' error.
Out of Scope Changes check ✅ Passed All changes are directly within scope: new plugin implementation, configuration type updates, and comprehensive unit tests for the cjsRequireRewrite feature.
Description check ✅ Passed The PR description comprehensively explains the problem (leaked __require calls), the root cause (Vite SSR lowering), and the solution (cjsRequireRewrite flag with two modes).
Title check ✅ Passed The title follows the Conventional Commits format with the type fix, scope build, and a concise description of the experimental runtime require rewrite change.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/ext-react

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
test/unit/cjs-require.test.ts (1)

27-144: ⚡ Quick win

Add coverage for single-quoted leaked requires

Please add a case for __require('react') (and/or another specifier) to lock in quote-agnostic rewrite behavior and avoid regressions.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/unit/cjs-require.test.ts` around lines 27 - 144, Add a new test case in
the describe block after the first it("rewrites a leaked __require() to the
bundled initializer") test to verify single-quoted leaked requires are handled
correctly. Create a test similar to the existing one but use single quotes in
the __require call (e.g., __require('react') instead of __require("react")) and
verify that the rewrite logic still produces the correct import statement and
variable assignment regardless of quote style. This ensures the rewrite behavior
is quote-agnostic and prevents regressions.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/build/plugins/cjs-require.ts`:
- Around line 28-29: The LEAK_RE regex pattern at the current location only
matches double-quoted require calls like __require("...") but fails to match
single-quoted variants like __require('...'). Update the LEAK_RE regex pattern
to match both single and double quotes around the require path argument.
Similarly, update the DEF_RE regex pattern (also mentioned in the review at line
85) to match both quote styles for the require definition pattern. Modify both
regex patterns to use a character class or alternation to capture both quote
types, ensuring that leak detection and rewriting work correctly regardless of
which quote style is used in the generated output.

---

Nitpick comments:
In `@test/unit/cjs-require.test.ts`:
- Around line 27-144: Add a new test case in the describe block after the first
it("rewrites a leaked __require() to the bundled initializer") test to verify
single-quoted leaked requires are handled correctly. Create a test similar to
the existing one but use single quotes in the __require call (e.g.,
__require('react') instead of __require("react")) and verify that the rewrite
logic still produces the correct import statement and variable assignment
regardless of quote style. This ensures the rewrite behavior is quote-agnostic
and prevents regressions.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e93b040a-265d-4630-91e6-616d1a2cd1fc

📥 Commits

Reviewing files that changed from the base of the PR and between f366b25 and 27169ad.

📒 Files selected for processing (4)
  • src/build/plugins.ts
  • src/build/plugins/cjs-require.ts
  • src/types/config.ts
  • test/unit/cjs-require.test.ts

Comment on lines +28 to +29
const LEAK_RE = /\b__require\(\s*"([^"]+)"\s*\)/g;
const DEF_RE = /\bvar (require_[A-Za-z0-9_$]+)\s*=[^\n]*__commonJS/g;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Handle single-quoted __require() calls too

LEAK_RE and the replacement regex only match __require("..."). If output uses __require('...'), the leak won’t be detected or rewritten, so runtime failures can persist in self-contained builds.

Suggested patch
-const LEAK_RE = /\b__require\(\s*"([^"]+)"\s*\)/g;
+const LEAK_RE = /\b__require\(\s*["']([^"'\\]+)["']\s*\)/g;
@@
-        const requireRe = new RegExp(`__require\\(\\s*"${escapeRe(spec)}"\\s*\\)`, "g");
+        const requireRe = new RegExp(
+          `__require\\(\\s*["']${escapeRe(spec)}["']\\s*\\)`,
+          "g"
+        );

Also applies to: 85-85

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/build/plugins/cjs-require.ts` around lines 28 - 29, The LEAK_RE regex
pattern at the current location only matches double-quoted require calls like
__require("...") but fails to match single-quoted variants like
__require('...'). Update the LEAK_RE regex pattern to match both single and
double quotes around the require path argument. Similarly, update the DEF_RE
regex pattern (also mentioned in the review at line 85) to match both quote
styles for the require definition pattern. Modify both regex patterns to use a
character class or alternation to capture both quote types, ensuring that leak
detection and rewriting work correctly regardless of which quote style is used
in the generated output.

@pkg-pr-new

pkg-pr-new Bot commented Jun 21, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/nitro@4365

commit: 65e5f56

@pi0 pi0 changed the title fix(build): rewrite leaked runtime require of bundled deps (#4171) fix(build): experimental flag to rewrite leaked runtime require of bundled deps (#4171) Jun 21, 2026
@pi0x pi0x added the bug Something isn't working (PRs; issues use the Bug type) label Sep 2, 2026
@pi0x pi0x changed the title fix(build): experimental flag to rewrite leaked runtime require of bundled deps (#4171) fix(build): add experimental flag to rewrite leaked runtime require of bundled deps (#4171) Sep 2, 2026
@pi0x pi0x added the v3 label Sep 2, 2026
letstri added a commit to letstri/permix that referenced this pull request Sep 5, 2026
* fix(docs): declare use-sync-external-store to keep react linked in SSR bundle

Every client-side navigation into /docs returned 500 in production:

    Error: Cannot find module 'react'
    Require stack:
    - /var/task/_ssr/rolldown-runtime-B4iAMlE-.mjs

The route loader's server function never resolved, so its `data` was
undefined and the route component threw "Cannot read properties of
undefined (reading 'path')". Direct hits on /docs/* were unaffected
because those pages are prerendered; only the `_serverFn` call made
during client-side navigation reached the crashing module.

`use-sync-external-store` is CJS-only and reaches the graph through
`@base-ui/react`, which `fumadocs-twoslash` started depending on in 3.3.
With pnpm the package is only visible through a nested `node_modules`,
so Vite's SSR pass cannot externalise it and inlines it instead —
leaving its internal `require("react")` as a runtime `__require("react")`
even though React is external. Nitro's second pass then bundles React
but cannot rewrite code that was already emitted, so the call survives
into `.vercel/output` and resolves against a `node_modules` that does
not exist on the Vercel function.

Declaring the package as a direct dependency hoists it to the root
`node_modules`, so Vite externalises it and Nitro links the require to
the bundled React copy. The built bundle now reads `require_react()`
instead of `__require("react")`.

This is a workaround for nitrojs/nitro#4171 (rolldown/rolldown#10643) and
can be dropped once nitrojs/nitro#4365 ships `experimental.cjsRequireRewrite`.

Co-Authored-By: Claude Opus 5 <[email protected]>

* chore: update dependencies

`taze -r -w major` across the workspace: vitest 5, @vitest/coverage-v8 5,
pnpm 12.3.4, tsdown 0.23, @tanstack/intent 0.3.8, @testing-library/jest-dom 7,
jsdom 30, lucide-react 1, fumadocs-twoslash 4, fumadocs 16.15.7,
@types/node 26, and assorted patch bumps. Followed by `pnpm dedupe`, which
collapses @trpc/server onto a single 11.18.0 copy — permix was resolving an
older 11.17.0 through its optional peer, and the two instances made the
tRPC middleware types structurally incompatible in the
express-trpc-react example.

TypeScript stays on ^6.0.3. Under 7.0.2 the permix build fails:
rolldown-plugin-dts rejects TS 7 with the `tsc` generator and falls back to
`tsgo`, which cannot emit declarations for the solution-style tsconfig.json
("tsgo did not generate dts file for ..."). svelte-check, @sveltejs/kit and
tsconfck also still want TS 5/6. Revisit once tsdown supports project
references with tsgo.

drizzle-orm is left alone — the registry request timed out during the run,
and the workspace intentionally tracks 1.0.0-rc rather than the 0.45.x
"latest" tag.

Co-Authored-By: Claude Opus 5 <[email protected]>

---------

Co-authored-by: Claude Opus 5 <[email protected]>
@pi0x

pi0x commented Sep 8, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto latest main locally (one conflict: main replaced sourcemapMinify() with the new sourcemap() plugin). Left the draft status alone and did not push.

Two things to consider:

  • generateBundle mutates chunk.code after sourcemaps are generated. Prepending an import shifts every line, so the chunk's sourcemap ends up off by one.
  • Detection depends on rolldown's exact codegen (__require(...), var require_x = ... __commonJS). With minify: true, or under the rollup builder, those identifiers differ, the regexes never match, and the plugin silently does nothing — not even the unresolved warning.

On the relation to #4094: they are complementary, not overlapping. #4094 makes a required package external and traced; this one handles the case where the package is already bundled. Worth noting in the issue that simply tracing react would fix Cannot find module but not the duplicate-instance "Invalid hook call" — the rewrite fixes both.

This comment was written by an AI assistant on behalf of the Nitro maintainers. Please double-check anything that looks wrong.

NickAkhmetov added a commit to hms-dbmi/scellop that referenced this pull request Sep 19, 2026
… to 5"

This reverts commit 2d19b13.

The demo's white screen is fixed at the source: dropping zustand/traditional
takes use-sync-external-store out of the graph, so there is no inlined CJS
package calling require("react") for Rolldown to leave behind. The demo bundle
now contains no require shim at all.

For the record, the workarounds that did not work here. Hoisting
use-sync-external-store, react and react-dom to the root node_modules via
publicHoistPattern produced byte-identical output, so the "not hoisted to root"
condition in rolldown/rolldown#10643 is not what triggers it in a browser
build. esmExternalRequirePlugin only rewrites requires for modules that are
external, and React is bundled here. Rolldown's `inject` cannot reach the call
either, because inside the CJS wrapper `require` is a bound local rather than a
free identifier. The remaining option was nitro's cjsRequireRewrite
(nitrojs/nitro#4365), a generateBundle pass that regex-rewrites the leaked call
to the bundled initializer -- which would have meant maintaining surgery over
minified output to keep a demo site alive.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
# Conflicts:
#	src/build/plugins.ts
s1gr1d added a commit to getsentry/sentry-javascript that referenced this pull request Oct 20, 2026
…ackages on Vite 8 (#25523)

We put pg into ssr.noExternal and that bundles `pg` and changes its CJS
imports. In the second bundling step, Rolldown in Vite 8 emits
`__require("pg-types")` for the dependency imports of pg (see [their
migration
guide](https://vite.dev/guide/migration#require-calls-for-externalized-modules)
mentioning `esmExternalRequirePlugin` - also check the linked rolldown
docs). As `__require` comes from `module.createRequire`, the bundlers
think it's a normal function variable, and not an import. Therefore, a
sub-dependency like `pg-types` cannot get into the final bundle.

The plugin now bundles exactly these `require()` calls. The user's
`ssr.external` entries and optional dependencies stay external. We
didn't use `esmExternalRequirePlugin`, because it breaks
function-exported CommonJS on Node < 23.

Stacked on #25359.

Fixes #25470


---

**Same problem: `__require()` of an external package stays in bundled
CommonJS**

- nitrojs/nitro#4171
- rolldown/rolldown#10643
- rolldown/rolldown#9407

**Workarounds and fixes in other tools**

- nitrojs/nitro#4365
- vitejs/vite#22618
- vitejs/vite#23759
- vitejs/vite#21969

**Existing Sentry issues**

- #24775
- #25339
@pi0

pi0 commented Oct 22, 2026

Copy link
Copy Markdown
Member

stalled

This branch was successfully deployed

1 active deployment
Preview — 65e5f56b Deployed Oct 13, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working (PRs; issues use the Bug type)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Cannot find module 'react' in Docker runner: use-sync-external-store/shim leaves __require('react') unresolved in SSR chunk

2 participants