node runtime_error ai_generated true

ReferenceError: fetch is not defined

ID: node/fetch-not-defined

Also available as: JSON · Markdown
95%Fix Rate
95%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
18 active

Root Cause

fetch() is experimental in Node 18, stable in Node 21+. Common when porting browser code.

generic

Workarounds

  1. 95% success Install node-fetch: npm install node-fetch
    import fetch from 'node-fetch';

    Sources: https://www.npmjs.com/package/node-fetch

  2. 90% success Upgrade to Node 21+ where fetch is stable, or use --experimental-fetch flag in Node 18
    nvm install 22 && nvm use 22
    # Or for Node 18: node --experimental-fetch app.js

    Sources: https://nodejs.org/api/globals.html#fetch

  3. 88% success Use undici (Node's built-in HTTP client): const { fetch } = require('undici')
    const { fetch } = require('undici')

    Sources: https://nodejs.org/api/globals.html#fetch

Dead Ends

Common approaches that don't work:

  1. Polyfill with whatwg-fetch 80% fail

    whatwg-fetch is browser-only, doesn't work in Node

  2. Use XMLHttpRequest 90% fail

    XMLHttpRequest doesn't exist in Node

Error Chain

Frequently confused with: