GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing blog.logrocket.com — The Fetch API is finally stable in Node.js - LogRocket Blog
2025-01-07
2144
#node
Elijah Asaolu
95667
See how LogRocket's Galileo AI surfaces the most severe issues for youNo signup requiredCheck it out
Editor’s note: This article was last reviewed and updated by Elijah Asaolu in January 2025 to cover common errors with Fetch not being defined or failing, and to provide guidance on making
The stabilization of the Fetch API in Node.js has been one of the most anticipated upgrades in recent years, as it provides a standardized and modern approach to performing HTTP requests in both the browser and server environments. To better understand why this is such a big deal, let’s explore the history of HTTP requests, how Fetch came to be, and what its stabilization means for Node developers. The evolution of HTTP requestsIn the early days of the web, it was difficult to perform asynchronous requests across websites; developers had to use clumsy approaches to interact across multiple networks. Internet Explorer 5 changed this in 1998 with the introduction of the The Introducing the Fetch APIIn 2015, the Fetch API was launched as a modern successor to Though the Fetch API has been around for a while now, it wasn’t included in the Node.js core because of some limitations. In a question answered by one of Node’s core contributors, it was noted that the browser’s Fetch API implementation is dependent on a browser-based Web Streams API and the Long before the addition of the Fetch API, the request module was the most popular method for making HTTP requests in Node. But the JavaScript ecosystem at large quickly evolved, and newly introduced patterns made the request module obsolete. A crucial example here is UndiciIn 2018, Undici was introduced as a newer and faster HTTP/1.1 client for Node.js, with support for pipelining and pooling, among other features. The Node core team worked hard on Undici, fixing performance issues, guaranteeing stability, and aligning the library with the Node project’s goals. Undici served as the foundation for Node.js’ native The Fetch API finds stability in Node.js v21As previously mentioned, Fetch was added to the Node.js core in v18. However, until v21, it was mostly experimental, with unavoidable bugs and instabilities. The stable release in v21 is a big milestone for developers, as it means that it has been tested thoroughly, so you can trust it to work in different scenarios without surprises. How to use the Fetch API in Node.jsThe Fetch API is provided as a high-level function, which means you don’t have to do any In its most basic version, it takes a URL, sends a fetch("http://example.com/api/endpoint")
.then((response) => {
// Do something with response
})
.catch((err) => {
// Handle error here
console.log("Unable to fetch -", err);
});
You can also change how the fetch("http://example.com/api/endpoint", {
method: "POST", // Specify request method
headers: {
// Customize request header here
"Content-Type": "application/json",
// . . .
},
body: JSON.stringify({
foo: "bar",
bar: "foo",
}),
// . . .
})
.then((res) => res.json())
.then((data) => {
console.log("Response data:", data);
})
.catch((err) => {
console.log("Unable to fetch -", err);
});
As shown in the updated example above, we’re now sending a Benefits of using the Fetch API in Node.jsThe fact that the Fetch API now comes prepackaged as an inbuilt Node module is extremely beneficial to the developer community. Some of these benefits include: No extra fetch packageInbuilt fetch for Node.js might mean the end for packages like node-fetch, got, cross-fetch, and many others that were built for the same purpose. This means you won’t have to conduct an Furthermore, node-fetch, currently the most popular fetch package for Node.js, was recently switched to an ESM-only package. This means you’re unable to import it with the Node Cross-platform familiarityDevelopers who have previously used the Fetch API on the front end will feel right at home using the inbuilt Faster implementationAs mentioned previously, the new Fetch implementation is also based on Undici. As a result, you should anticipate improved performance from the Fetch API, as well. Drawbacks of using the Fetch API in Node.jsThe browser’s Fetch API has some drawbacks in and of itself, and these will undoubtedly be transferred to the new Node.js Fetch implementation: Lack of built-in progress eventsThe Node.js Fetch API does not have built-in support for progress events during file uploads or downloads. Developers who want fine-grained control over monitoring progress may find this limitation difficult to overcome and may need to look into alternative libraries or solutions. Limited support for older Node.js versionsWhile the Fetch API is stable in newer Node.js versions, projects using earlier Node.js versions may encounter compatibility difficulties. Developers working in environments where upgrading Node.js is not possible may be forced to rely on alternative libraries or develop workarounds. Complexity in handling cookiesThe Fetch API’s approach to cookie management is based on browser behavior, which may result in unexpected outcomes in a Node.js environment. When dealing with cookies, developers must exercise caution and ensure accurate configuration for specific use cases. Migrating to the official, stable FetchMigrating to the official, stable Node.js Fetch API is pretty straightforward, as outlined below: Update Node.js versionFirst, ensure that your Node.js version is at least v21 or higher. You can check your current Node.js version using the following command: node -v If your Node.js version is below version 21, upgrade to the latest version. You can download the latest version directly from the official Node.js website or use a version manager like nvm (Node Version Manager). For example, you can use NVM to list all available versions of Node.js by running the following command: nvm ls-remote Once you’ve seen a preferred version, you can then install it by running: nvm install x.y.z # E.g to install v22.13.0: nvm install v22.13.0 Remove dependency on external librariesIf you were using an external library for making requests in Node.js, such as npm uninstall node-fetch Update code to use native FetchReplace any code that currently utilizes an external library with the native Here’s what your code looked like before the update: And what it looks like after you update to use native Fetch: fetch("https://api.example.com/data")
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error("Error:", error));
Adjust options and headersAs required, review and adjust any options or headers in your requests. The native Fetch API may differ in behavior or provide extra functionality, so consult the official documentation for any specific requirements. Testing and debuggingAfter you’ve made these changes, thoroughly test your application to check that the migration to the native Fetch API didn’t cause any problems. Take great care with error handling, timeouts, and any custom logic associated with HTTP requests. Common errors when using Fetch in Node.jsMany developers encounter errors when trying to use Fetch in Node.js. Let’s look at some of the most common issues and how to resolve them. Missing Fetch in older Node.js versionsA common issue is the Furthermore, if you’re using an experimental version (v18–v20), you’ll need to run your app with the experimental flag: node --experimental-fetch example.js Additionally, for legacy projects where upgrading Node.js isn’t an option, you can use a library like node-fetch to add Fetch support to your project. Network and CORS issues in FetchAnother common error is To resolve this, verify that the endpoint URL is valid. Also ensure the server is configured to allow CORS by adding the appropriate headers or using techniques like proxy middleware. Invalid JSON in Fetch responseSimilar to the above, To resolve, confirm that the endpoint is returning a valid JSON structure. In some cases, the server might return a fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error(`Request failed with status: ${response.status}`);
}
return response.json(); // Use .blob(), .bytes(), or .text() if required
})
.then(data => console.log(data))
.catch(error => console.error('Fetch error:', error));
Unmanaged cookiesFetch in Node.js mimics browser-like behavior; however, unlike browsers, it doesn’t automatically handle cookies, i.e., cookies aren’t stored or sent unless you manage them yourself. For example, if an API relies on cookies for authentication, you’ll need to manually include them in your requests or use a library such as fetch-cookie or tough-cookie to manage them. Request timeoutsFetch doesn’t natively support timeouts, so if a server takes too long to respond, your request might hang indefinitely. To avoid this, you can use const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 5000); // Timeout after 5 seconds
fetch("http://example.com/api", { signal: controller.signal })
.then((response) => response.json())
.catch((err) => console.log("Fetch error:", err));
This way, you have full control over how long to wait for a response before canceling the request. ConclusionThe stabilization of the Node.js Fetch API, made possible by the tireless efforts of the Node.js core team and the key role played by the high-performance HTTP client library Undici, represents a big step forward for developers. The stable release also means you can now use it without the fear of bugs or unexpected issues, and you can enjoy a consistent experience when making HTTP requests in both browser and server environments. 200s only
|
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |