ReferenceError:
nodejs
July 7, 20222 min read

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.

Share this blog
Tagged in :
nodejs
Like what you read?
Subscribe to our Newsletter
Subscribe to our email newsletter and unlock access to members-only content and exclusive updates.
About the Author
Satvik
Satvik
Entrepreneur
Satvik is a passionate developer turned Entrepreneur. He is fascinated by JavaScript, Operating System, Deep Learning, AR/VR. He has published several research papers and applied for patents in the field as well. Satvik is a speaker in conferences, meetups talking about Artificial Intelligence, JavaScript and related subjects. His goal is to solve complex problems that people face with automation. Related projects can be seen at - [Projects](/projects)
View all articles
Previous Article