Troubleshooting ReferenceError: fetch is not defined

Node.js Fetch API is a module designed for developers to facilitate sending API calls and receiving responses from servers in Node.js applications. Originally, this capability was not directly incorporated into Node.js owing to specific limitations or limits.

Nevertheless, the fetch API has been effectively implemented as a stable and supported functionality in Node.js version 18. This integration offers a more efficient and practical approach to interacting with Node.js applications’ APIs by streamlining the process of submitting requests and managing answers. Now, developers may improve the effectiveness of managing server connection activities in their Node.js apps by utilizing the fetch API.

Understanding ReferenceError: fetch is not defined

The “fetch is not defined” issue occurs due to the lack of native support for the fetch() method in Node.js versions previous to v18.0.

Although it was included in v18.0 of Node.js. Before that if you attempt to use the fetch API directly in Node.js, you will receive the “ReferenceError: fetch is not defined” error. As a result, practitioners had to create various ways to enable the usage of the fetch() function inside the Node.js environment.

Image Of Error Fetch Is Not Defined

In this article, we are going to explore multiple solutions for these errors.

Fixing ReferenceError: fetch is not defined

Here are some methods that can help you resolve this error.

Method 1: Upgrading the Version of Node.js

The simple approach is to upgrade your Node.js version to 18.0 or a higher LTS version because these versions of Node include native support for the fetch API.

The very recent addition of this API to several browsers has been one of the things that have prevented developers from progressing. This is why the Node.js addition of fetch() is a step in the right direction toward a more uniform HTTP stack across platforms and devices.

Image for using fetch Api

In the above example, we are using the Fetch API in Node.js on version 18.0, in which the getData function makes an HTTP GET call to the given URL. After that, it splits the response into Promise chaining. The response is converted to JSON format by the first .then(), and the outcome is logged to the console by the second. The function is finally executed, starting the API request and reporting the information that was collected from the server.

To update the version of nNde.js you can download the installer of the LTS (long-term supported) version from the Node.js official website.

For detailed tuitorial on updating Node.js, check out: How to Update Node Version on Windows, Linux, and macOS.

Method 2: Node-fetch Library

A lightweight module called node-fetch gives Node.js apps a quick and easy method to send HTTP requests using a syntax similar to the Fetch API. The simplicity of this package, which enables developers to make use of a uniform API for submitting HTTP requests across client-side and server-side code, is an effective case for its use. Furthermore, promises are supported by the package, which makes using async/await syntax to handle asynchronous tasks simple.

Below is a step-by-step guide for using node-fetch:

STEP 1) Install the ‘node-fetch’ module using the below command.

npm install node-fetch

STEP 2) You may now utilize the fetch() method from the node-fetch package. We imported the ‘node-fetch’ module using the ECMAScript modules syntax.

import fetch from "node-fetch"

STEP 3) Now you can utilize the fetch() function in a manner as you would within a web browser. Let me provide you with an illustration of how to make a GET request.

Image of using node-fetch package

In the above example, we have demonstrated how to use the Fetch API with the help of the ‘node-fetch’ module. The ‘fetchApi’ function is defined, which contains the logic for sending an HTTP request using the Fetch API.

Within the ‘fetchApi’ method, the ‘fetch’ function is used to send a GET request to the supplied URL. The response is then processed using Promise chaining. The first ‘then’ block extracts the JSON data from the response, and the second ‘then’ block logs the parsed JSON data to the console.

Method 3: Use a Different HTTP Library

Consider using alternative HTTP request libraries like Axios, which are designed to work seamlessly in both browser and Node.js environments.

Axios is a JavaScript library made for executing HTTP requests in Node.js and browser contexts. Developers often prefer Axios for several reasons such as:

  1. It has Promise support, which makes asynchronous actions simple to manage with the help of async/await capabilities.
  2. Axios automatically transforms JSON data, simplifying the process of sending and receiving data.
  3. It also has capabilities like global request and response processing interceptors, which provide flexibility and power for a range of use scenarios.

Below is a step-by-step guide for using Axios:

STEP 1) Install the Axios library using npm.

npm install axios

STEP 2) This line uses ECMAScript modules syntax to import the ‘axios’ library, a common HTTP client for performing requests in both browser and Node.js contexts.

import axios from "axios"

STEP 3) Now, you can use the Axios library to make HTTP requests. Here’s an example of making a simple GET request.

Image of using axios for fetching data

In this above example, we have demonstrated how to fetch an API with the help of the ‘axios’ module. The ‘fetchApi’ function is defined. Within the ‘fetchApi’ method, the ‘axios.get’ function is used to send a GET request to the supplied URL. It fetches data from a placeholder API endpoint and logs the resulting JSON to the console. Axios makes it easier to make HTTP queries by offering a simple, promise-based syntax for managing replies.

Benefits of Using the Fetch API in Node.js

The Fetch API is now available as a pre-configured Node module, which benefits the developer community. Among the benefits are:

  1. Ease of acceptance for frontend developers – Frontend developers who have experience using the Fetch API on the client side will find the syntax for making API queries on the server side very familiar. Consequently, it becomes more convenient and intuitive to use compared to packages that offer functionality.
  2. Faster implementation – The Node.js Fetch API implementation is based on Undici, a fast and high-performance HTTP client. Using Undici improves the overall efficiency of the Fetch API in Node.js, resulting in quicker and more reliable HTTP request processing.
  3. No Additional Fetch Packages – The built-in integration of the Fetch API decreases the reliance on packages such, as ‘node fetch’ or ‘cross fetch’ which were previously required to enable Fetch functionality in Node.js. Now developers can depend on the Fetch API reducing the necessity for external dependencies.

Conclusion

The “fetch is not defined” problem in Node.js is a typical stumbling block for developers who mostly work with browser-based JavaScript. Understanding the version of Node.js being utilized is critical in determining the best approach. Upgrading to Node.js version 18 or above gives you direct access to the fetch() API, which eliminates the requirement for additional modules. However, for previous Node.js versions, third-party modules or other libraries are required to successfully use this method. By taking the proper method, developers may avoid this problem and manage HTTP requests in their Node.js apps flawlessly.

Reference

https://stackoverflow.com/questions/48433783/referenceerror-fetch-is-not-defined

Anurag Pandey
Anurag Pandey
Articles: 16