If you copied a fetch() example from the browser into a Node.js script and got:
ReferenceError: fetch is not defined
you did nothing wrong. fetch is a browser API. It only became built into Node.js starting with Node 18.
Three quick ways to know what you are dealing with:
node -v
Case 1 — Node 18 or newer. fetch is global. If it still fails, you are probably running an old Node from another shell or an outdated CI image. Check the version the script actually runs with, not the one you think you have.
Case 2 — Node 16 or older. Either upgrade Node (best), or add a polyfill:
import fetch from 'node-fetch';
Case 3 — wrong context. Running the file with a bundler, a serverless runtime or a test runner can shadow the global. Log typeof fetch at the top of the file to confirm.
The mental model that saves time: the error is about the runtime, not your code. Identify the runtime first, then decide between upgrade and polyfill.
I wrote a full French walkthrough with the Node version table, the polyfill setup and the common CI trap here:
https://gogokodo.com/fetch-is-not-defined-referenceerror-nodejs-solution
Top comments (0)