Skip to content

fix(cloudflare): stub cloudflare:* modules during prerendering - #5197

Open
semanym wants to merge 1 commit into
nitrojs:mainfrom
semanym:fix/cloudflare-prerender-workers-stubs
Open

semanym wants to merge 1 commit into
nitrojs:mainfrom
semanym:fix/cloudflare-prerender-workers-stubs

Conversation

@semanym

@semanym semanym commented Nov 30, 2026

Copy link
Copy Markdown

🔗 Linked issue

Resolves #5024

❓ Type of change

  • 📖 Documentation (updates to the documentation, readme, or JSdoc annotations)
  • 🐞 Bug fix (a non-breaking change that fixes an issue)
  • 👌 Enhancement (improving an existing functionality like performance)
  • ✨ New feature (a non-breaking change that adds functionality)
  • 🧹 Chore (updates to the build process or auxiliary tools and libraries)
  • ⚠️ Breaking change (fix or feature that would cause existing functionality to change)

📚 Description

When a Cloudflare Worker or Pages app exports Worker-only classes from server.ts (for example a DurableObject, WorkerEntrypoint, or WorkflowEntrypoint importing cloudflare:workers) and also prerenders routes, the Node.js nitro-prerender sub-build still imports server.ts (since server.ts can also carry a default handler or startup logic). Because nitro-prerender runs under Node.js without the Cloudflare preset's cloudflare:* handling, the prerender build logs UNRESOLVED_IMPORT and the prerender worker crashes on startup with ERR_UNSUPPORTED_ESM_URL_SCHEME (Received protocol 'cloudflare:').

This PR fixes the issue by:

  • Adding minimal Node.js prerender stubs under src/presets/cloudflare/runtime/_prerender/ for the four cloudflare:* builtin modules listed in unenvCfExternals (cloudflare:workers, cloudflare:sockets, cloudflare:email, and cloudflare:workflows). Class base exports (DurableObject, WorkerEntrypoint, WorkflowEntrypoint, WorkflowStep, RpcTarget, RpcStub, EmailMessage) can be subclassed at module load time and throw an explicit error if instantiated during prerendering; NonRetryableError extends Error; env/exports/cache/tracing are empty objects; and runtime-only functions (connect, waitUntil, withEnv, withExports, withEnvAndExports) throw explicit errors if invoked.
  • Exporting unenvCfPrerender in src/presets/cloudflare/unenv/preset.ts (extensionless paths under presetsDir, matching _durable and telemetry/plugin so both pnpm build and pnpm stub resolve cleanly).
  • Registering a prerender:init hook on cloudflare-pages and cloudflare-module (inherited by cloudflare-durable) that applies extendEnv(prerenderer, unenvCfPrerender). Because extendEnv layers sit below user config, user-defined $prerender.alias overrides still take precedence, and the main Worker bundle continues to emit real external cloudflare:* imports.
  • Rewriting URI-scheme aliases (such as cloudflare:*) in Rspack's beforeResolve hook (src/build/rspack/config.ts, src/build/rspack/_plugin.ts) because Rspack treats URI-scheme requests as URI resources and skips resolve.alias.
  • Adding regression tests in test/prerender/cloudflare-exports.test.ts covering cloudflare-module (with real Miniflare Durable Object execution), cloudflare-pages, the Vite builder, server.ts with both default and named exports, $prerender.alias precedence, the unbundled prerenderer (builder: false), and stub unit behavior across Rollup, Rolldown, and Rspack.

📝 Checklist

  • I have linked an issue or discussion.
  • I have updated the documentation accordingly.

🤖 Generated with Claude Code

When a Cloudflare Worker or Pages app re-exports Worker-only classes (such as
Durable Objects or Workflows importing `cloudflare:workers`) from `server.ts`,
the Node-based `nitro-prerender` sub-build still loads `server.ts` and fails
with `ERR_UNSUPPORTED_ESM_URL_SCHEME` (`Received protocol 'cloudflare:'`).

Register a `prerender:init` hook on the `cloudflare-module` (and inherited
`cloudflare-durable`) and `cloudflare-pages` presets that adds Node.js stubs
for `cloudflare:workers`, `cloudflare:sockets`, `cloudflare:email`, and
`cloudflare:workflows` via `extendEnv`. Because preset env layers sit below
user options, user-defined `$prerender.alias` overrides still win, and the
final Worker bundle keeps real external `cloudflare:*` imports untouched.
Also rewrite URI-scheme aliases in Rspack's `beforeResolve` hook so both
built-in and user `cloudflare:*` aliases work under the Rspack builder.

Fixes nitrojs#5024

Co-Authored-By: Claude Code <noreply@anthropic.com>
@semanym
semanym requested a review from pi0 as a code owner November 30, 2026 02:54
@vercel

vercel Bot commented Nov 30, 2026

Copy link
Copy Markdown

@semanym is attempting to deploy a commit to the Nitro Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Cloudflare presets now provide prerender aliases and runtime stubs for Cloudflare APIs. Rspack passes non-external URI-scheme aliases to its resolver. Tests cover prerender builds, server entry exports, user aliases, and stub behavior.

Changes: Cloudflare prerender resolution

Layer / File(s) Summary
Cloudflare prerender stubs and aliases
src/presets/cloudflare/runtime/_prerender/*, src/presets/cloudflare/unenv/preset.ts, test/prerender/cloudflare-exports.test.ts
The prerender preset maps four Cloudflare modules to runtime stubs. The stubs define API behavior for prerendering, and tests check those behaviors.
Preset and resolver wiring
src/build/rspack/_plugin.ts, src/build/rspack/config.ts, src/presets/cloudflare/preset.ts, test/prerender/cloudflare-exports.test.ts
Cloudflare Pages and module presets extend the prerender environment with the Cloudflare prerender preset. Rspack passes matching non-external scheme aliases to its resolver, which replaces matching requests before resolution.
Build and export integration coverage
test/prerender/cloudflare-exports.test.ts
Tests cover Cloudflare module and Pages builds, Vite and unbundled prerendering, server entry exports, and a user-provided prerender alias.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix · Severity of issue fixed: Medium

Possibly related PRs

  • nitrojs/nitro#4942: Introduces the Rspack builder, including the resolver code extended here.

Suggested labels: bug, preset:cloudflare

Merge Risk: Minimal · up to fa899

The change lets Cloudflare prerender builds resolve Worker-only imports through stubs while the Worker bundle keeps the real modules. No actionable merge risk remains.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title "fix(cloudflare): stub cloudflare:* modules during prerendering" follows the conventional commits format (type fix, scope cloudflare, description). It matches the main change: Node.js prer…
Description check Passed The description states the problem (server.ts re-exporting Worker-only classes that import cloudflare:* breaks the Node.js prerender build) and lists the changes: runtime prerender stubs, the unenvCfP…
Linked Issues check Passed [#5024] The issue requires that a prerendered Cloudflare build succeeds when server.ts re-exports a Worker-only class that imports cloudflare:workers. The diff adds a prerender-only alias set, unenvCf…
Out of Scope Changes check Passed The changes support the #5024 objective. The unenv/preset.ts and preset.ts changes define and register the prerender stubs. The runtime/_prerender stub files (workers, workflows, email, sockets) suppl…
Full details: Title check

Explanation

The title "fix(cloudflare): stub cloudflare:* modules during prerendering" follows the conventional commits format (type fix, scope cloudflare, description). It matches the main change: Node.js prerender stubs for the cloudflare:* modules, registered through prerender:init for the Cloudflare presets.

Full details: Description check

Explanation

The description states the problem (server.ts re-exporting Worker-only classes that import cloudflare:* breaks the Node.js prerender build) and lists the changes: runtime prerender stubs, the unenvCfPrerender preset, the prerender:init hooks, the Rspack beforeResolve alias rewrite, and regression tests. These match the changeset.

Full details: Linked Issues check

Explanation

[#5024] The issue requires that a prerendered Cloudflare build succeeds when server.ts re-exports a Worker-only class that imports cloudflare:workers. The diff adds a prerender-only alias set, unenvCfPrerender, in src/presets/cloudflare/unenv/preset.ts. It maps cloudflare:email, cloudflare:sockets, cloudflare:workers, and cloudflare:workflows to Node.js stubs under runtime/_prerender/. src/presets/cloudflare/preset.ts applies this set through a prerender:init hook on cloudflare-pages and cloudflare-module. cloudflare-durable inherits the hook. The issue asks for the preset's cloudflare:* handling to reach the prerender build. This change does that. The issue's workaround also keeps the real module in the Worker bundle. The PR keeps that behavior by applying the alias only through the prerenderer env. The stub files and the test file were not read in full. The summary reports regression tests for the Miniflare Durable Object case, the Vite builder, and $prerender.alias precedence. Those tests were not run, so runtime behavior is supported by the code path and the summary, not by execution.

Full details: Out of Scope Changes check

Explanation

The changes support the #5024 objective. The unenv/preset.ts and preset.ts changes define and register the prerender stubs. The runtime/_prerender stub files (workers, workflows, email, sockets) supply the modules the stubs alias. The src/build/rspack/config.ts and _plugin.ts changes add schemeAliases. These rewrite URI-scheme aliases in beforeResolve, because Rspack skips resolve.alias for scheme requests. Without this, the prerender alias would not apply under Rspack. The test file covers the listed behavior. The Rspack change applies to every scheme alias that is not externalized. That broader effect is a side effect of the same mechanism, not an unrelated change. No unrelated change was found in the inspected hunks.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
Fix failing CI checks

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 6e44e83f-8863-4b7f-bdbe-7e4e7b71a38f
Commits

Reviewing files that changed from the base of the PR and between 925c135 and fa8999f.

Files selected for processing: 9

  • src/build/rspack/_plugin.ts
  • src/build/rspack/config.ts
  • src/presets/cloudflare/preset.ts
  • src/presets/cloudflare/runtime/_prerender/email.ts
  • src/presets/cloudflare/runtime/_prerender/sockets.ts
  • src/presets/cloudflare/runtime/_prerender/workers.ts
  • src/presets/cloudflare/runtime/_prerender/workflows.ts
  • src/presets/cloudflare/unenv/preset.ts
  • test/prerender/cloudflare-exports.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

cloudflare: server entry exports break the prerender build when they import cloudflare:workers

1 participant