ReferenceError: fetch is not defined
ReferenceError: fetch is not defined in Node.js
Does your error 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.
In case you are already using the newer version of Node.js i.e., Node.js >
v18, then, you should not see the error ReferenceError: fetch is not defined in Node.js
.
In conclusion, the ReferenceError occurs if you are using an older version (<
18) of Node.js and it can be resolved by using node-fetch library or use alternatives. In case you are using Node.js v17, then you can use the experimental flag as mentioned above to make it work. In case you are using Node.js v18 and above, you should be able to use it by default as its available in the global scope.