- Published on
ReferenceError: fetch is not defined
ReferenceError: fetch is not defined in Node.js
Does your log look something like this?
const res = await fetch("https://nodejs.org/api/documentation.json", {
^
ReferenceError: fetch is not defined
You might see this issue often if you are running on an older version of Node.js. fetch
came to Node.js v17 under experimental flag --experimental-fetch. In Node.js v18, the experimental fetch API is available on the global scope by default. The implementation is based upon undici, an HTTP/1.1 client written for Node.js by contributors to the project.
const res = await fetch('https://nodejs.org/api/documentation.json');
if (res.ok) {
const data = await res.json();
console.log(data);
}
Through this addition, the following globals are made available: fetch
, FormData
, Headers
, Request
, Response
.
Disable this API with the --no-experimental-fetch
command-line flag.