Skip to content

[cloudflare] astro dev: bare require("node-fetch") in workerd under Vite 8 — node-fetch is in the server optimizeDeps.exclude #18436

Closed

Description

@rotexhawk

Astro Info

Astro                    v7.4.0
Vite                     v8.3.4
Node                     v24.13.1
System                   macOS (arm64)
Package Manager          pnpm
Output                   server
Adapter                  @astrojs/cloudflare (v14.4.0)
Integrations             none

If this issue only occurs in one browser, which browser is a problem?

No response

Describe the Bug

astro dev with @astrojs/cloudflare 14 fails on the first request when a server-side dependency is CommonJS that requires node-fetch. cross-fetch is the common case: its Node entry does require('node-fetch') at module load.

Internal server error: Calling `require` for "node-fetch" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details.
    at runInRunnerObject (workers/runner-worker/index.js:107:3)
    at Object.getComponentByRoute (.../node_modules/.vite/deps_ssr/astro_app_entrypoint_dev.js:52:9)
    ...

Cause. vite-plugin-environment hard-codes optimizeDeps.exclude: ["node-fetch"] for the server environments (ssr, astro, prerender, client) whenever dependency discovery is on (dist/vite-plugin-environment/index.js, the noDiscovery === false branch). So Vite pre-bundles cross-fetch for the workerd ssr environment but leaves node-fetch external. Under Vite 8 (Rolldown), an external that a bundled CommonJS dependency requires stays a bare require("node-fetch") call, and workerd has no require.

astro build is fine; only dev is affected.

Workaround (confirmed in the repro below): a post plugin that removes that one exclude for the ssr environment. After that, node-fetch is bundled into the optimized dep and the page renders.

const keepNodeFetch = {
  name: 'keep-node-fetch',
  enforce: 'post',
  configEnvironment(name, options) {
    if (name !== 'ssr' || !options.optimizeDeps?.exclude) return;
    options.optimizeDeps.exclude = options.optimizeDeps.exclude.filter((id) => id !== 'node-fetch');
  },
};
// defineConfig({ ..., vite: { plugins: [keepNodeFetch] } })

Re-adding node-fetch to optimizeDeps.include, changing resolve.mainFields, and Rolldown's esmExternalRequirePlugin did not fix it.

It's unclear whether the exclude is still needed for the workerd environment. If it exists for the Node runtime, it probably shouldn't apply when the adapter runs ssr in workerd.

What's the expected result?

astro dev serves the page, as astro build does and as it did on Astro 6 / Vite 7.

Link to Minimal Reproducible Example

StackBlitz doesn't support @astrojs/cloudflare, so here are the four files inline. Run pnpm install, then pnpm dev, then request /. It returns 500 with the error above. Add the workaround plugin to the config and it returns 200.

package.json

{
  "name": "astro-node-fetch-repro",
  "type": "module",
  "private": true,
  "scripts": { "dev": "astro dev", "build": "astro build" },
  "dependencies": {
    "astro": "7.4.0",
    "@astrojs/cloudflare": "14.4.0",
    "cross-fetch": "4.1.0",
    "wrangler": "*"
  }
}

astro.config.mjs

import { defineConfig } from 'astro/config';
import cloudflare from '@astrojs/cloudflare';

export default defineConfig({
  output: 'server',
  adapter: cloudflare(),
});

src/pages/index.astro

---
// cross-fetch's CommonJS entry does `require('node-fetch')` at module load.
import crossFetch from 'cross-fetch';
---
<p>{typeof crossFetch}</p>

wrangler.jsonc

{ "name": "astro-node-fetch-repro", "compatibility_date": "2026-10-01", "compatibility_flags": ["nodejs_compat"] }

Participation

  • I am willing to submit a pull request for this issue.

Activity

  1. added
    triage: in progress
    on Oct 18, 2026
  2. astro-factory commented on Oct 18, 2026

    @astro-factory
    Contributor

    Triage complete

    • Prepare the workspace: ready
    • Install dependencies: complete
    • Build the project: complete
    • Reproduce the issue: confirmed
    • Diagnose the cause: high confidence
    • Verify the diagnosis: bug
    • Attempt a fix: verified
    • Publish the result: set triage: fix pending

    • Reproduced: Yes
    • Exploration: Yes — View branch
    • Unit Test: Yes — packages/astro/test/units/vite-plugin-environment/server-entries.test.ts
    • Priority: P2: Has Workaround. This only affects astro dev with the Cloudflare adapter when a CJS dependency requires node-fetch. The reporter's small Vite plugin works around it completely.

    In packages/astro/src/vite-plugin-environment/index.ts (around line 91), server environments that turn on dependency discovery (noDiscovery === false) get a hard-coded optimizeDeps.exclude: ['node-fetch']. In practice that means the Cloudflare workerd environments. So when Vite bundles cross-fetch for the workerd ssr environment, node-fetch stays external, and Rolldown emits __require("node-fetch") in the optimized dep. That call throws because workerd has no require. Git history suggests the exclude is a leftover: it used to be in the top-level (client) optimizeDeps config in create-vite.ts, and the Environment API refactor (#14306) moved it as-is into the server environment branch. No comment or test explains why it's needed there.

    I found a potential fix for this issue. The branch removes 'node-fetch' from that exclude, so the optimizer bundles node-fetch into deps that require it. With the reporter's config unchanged, GET / now returns 200. The existing Cloudflare dev tests pass. This needs human review.

    Try this fix

    You can test this fix right now without waiting for a release:

    # astro
    npm i https://pkg.pr.new/astro@4fac8a0

    If this fixes your issue, please leave a comment letting us know (for example
    "confirmed, this fixes it"). A pull request will then be opened to get it merged.

    Full Triage Report

    Issue summary

    astro dev with @astrojs/cloudflare 14 fails on the first request when a server-side CJS dependency calls require('node-fetch'), for example cross-fetch:

    Internal server error: Calling `require` for "node-fetch" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details.
    

    astro build works. Expected: astro dev serves the page, like astro build does and like Astro 6 / Vite 7 did.

    Environment

    • Reporter: Astro 7.4.0, Vite 8.3.4, Node 24.13.1, macOS arm64, pnpm, @astrojs/cloudflare 14.4.0, output server
    • Triage: monorepo main (astro 7.4.0 and @astrojs/cloudflare 14.4.0 linked from the workspace), Vite 8.3.4, wrangler 4.149.0, workerd 1.20261006.1, cross-fetch 4.1.0, Node 22.23.2, pnpm 10.34.6, Linux

    Steps to reproduce

    1. astro.config.mjs: output: 'server', adapter: cloudflare()
    2. src/pages/index.astro: import crossFetch from 'cross-fetch'; and render <p>{typeof crossFetch}</p>
    3. wrangler.jsonc: { "name": "astro-node-fetch-repro", "compatibility_date": "2026-10-01", "compatibility_flags": ["nodejs_compat"] }
    4. pnpm install, astro dev, then request /

    Result

    • 500 on every request:
    [vite] dependency optimized: cross-fetch
    [ERROR] [vite] Internal server error: Calling `require` for "node-fetch" in an environment that doesn't expose the `require` function. ...
        at runInRunnerObject (workers/runner-worker/index.js:107:3)
        at Object.getComponentByRoute (.../node_modules/.vite/deps_ssr/astro_app_entrypoint_dev.js:52:9)
        at matchRoute (...astro_app_entrypoint_dev.js:234:10)
        at DevFacadeApp.devMatch (...astro_app_entrypoint_dev.js:299:24)
        at Object.handle [as fetch] (.../deps_ssr/@astrojs_cloudflare_entrypoints_server.js:386:18)
    
    • node_modules/.vite/deps_ssr/cross-fetch.js contains var nodeFetch = __require("node-fetch");
    • With the reporter's workaround plugin (which drops node-fetch from ssr's optimizeDeps.exclude), / returns 200.
    • astro build succeeds.

    Diagnosis

    • File: packages/astro/src/vite-plugin-environment/index.ts, lines 82-93:
    if (_options.optimizeDeps?.noDiscovery === false) {
      finalEnvironmentOptions.optimizeDeps = {
        entries: [...],
        extensions: ['.mts'],
        include: [],
        exclude: ['node-fetch'],
      };
    }
    • This branch only runs for environments with discovery enabled, which are the Cloudflare workerd environments. Excluding node-fetch keeps it external. Rolldown then leaves a __require("node-fetch") call inside the pre-bundled CJS dependency, and that call throws in workerd.
    • History: Before Environment API #14306 (Environment API, 141c4a2), the exclude lived in the top-level optimizeDeps in create-vite.ts (exclude: ['astro', 'node-fetch']), which only affected the client optimizer. Environment API #14306 copied it into the server environment branch. fix: add Cloudflare e2e tests w/ pre-optimized deps #14975 (f73fab4) later removed 'astro' but kept 'node-fetch'. No comment or test explains why node-fetch is excluded for server environments.
    • Confidence: high.

    Verification

    • Verdict: bug (high confidence). Nothing in the code, tests, or docs gives a reason for this behavior. It looks like a side effect of moving a legacy client-optimizer setting into the server environments. Removing it has no evident downside, since node-fetch can't load in workerd with the exclude in place anyway.

    Fix

    --- a/packages/astro/src/vite-plugin-environment/index.ts
    +++ b/packages/astro/src/vite-plugin-environment/index.ts
    @@ -88,7 +88,7 @@
     						extensions: ['.mts'],
     						include: [],
    -						exclude: ['node-fetch'],
    +						exclude: [],
     					};
    • Unit test: a new test in packages/astro/test/units/vite-plugin-environment/server-entries.test.ts, "does not exclude node-fetch from server dependency optimization". It checks that configEnvironment('ssr', { optimizeDeps: { noDiscovery: false } }) doesn't put node-fetch in exclude. All 12 tests in that folder pass.
    • Repro: after rebuilding, astro dev with the original config (no workaround) returns 200 and renders <p>function</p>.
    • Regression check: packages/integrations/cloudflare/test/astro-dev-platform.test.ts passes 8/8. Biome is clean on the changed files.
    • Changeset: .changeset/fix-cloudflare-node-fetch.md (astro: patch).
    • Alternative considered: keep the exclude for non-workerd environments only. Not done, because nothing appears to need it, and Node dev environments never reach this branch.

    This report was made by an LLM. The analysis may be wrong, and the potential fix might not work, but is intended as a starting point for exploring the issue.

  3. added
    - P2: has workaround
    pkg: astro
    pkg: cloudflare
    triage: fix pending
    and removed
    triage: in progress
    on Oct 18, 2026
  4. rotexhawk commented on Oct 18, 2026

    @rotexhawk
    Author

    Confirmed, this fixes it. Tested with astro@https://pkg.pr.new/astro@4fac8a0, without the workaround plugin:

    • The minimal repro above: astro dev now serves / with 200 and renders <p>function</p>, with no require error. astro build still passes.
    • The real app where we first hit this: @astrojs/cloudflare 14.4.0 with copc → cross-fetch → node-fetch, workaround removed. astro dev boots, the SSR pages return 200, and our end-to-end funnel test passes.

    Thanks for the quick turnaround.

  5. added
    triage: fix verified
    and removed
    triage: fix pending
    on Oct 18, 2026
  6. astro-factory commented on Oct 18, 2026

    @astro-factory
    Contributor

    The fix has been verified! A pull request has been created: #18438

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

Metadata

Metadata

Assignees

Labels

- P2: has workaroundpkg: astropkg: cloudflaretriage: fix verified

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions