CodeWithYou

Finally, we can use fetch API in node.js

Published on
Authors
we can use fetch API in node.js

Photo by Dan Gribbin

Introduction

Node.js v16.15.0 has been released with the fetch API. This is exciting news for developers who want to use fetch API in node.js. In this article, we will see how to use fetch API in node.js.

What is fetch API?

The fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network. Use the fetch() method to make a request to a server and get a response back. The fetch() method is a modern replacement for XMLHttpRequest. It is a promise-based API, which means that it is asynchronous and returns a promise.

How to use fetch API in node.js?

The Fetch API is provided as a high-level function, and in its most basic version, it takes a URL and produces a promise that resolves to the response:

fetch('https://example.com/movies.json')
  .then((response) => response.json())
  .then((data) => console.log(data))

you can also use async/await syntax:

async function fetchAsync() {
  let response = await fetch('https://example.com/movies.json')
  let data = await response.json()
  return data
}
fetchAsync().then((data) => console.log(data))

Benefits of using the Fetch API in Node.js

No need to install any third-party library

Fetch API now is inbuilt in node.js. So, we don't need to install any third-party library to use fetch API in node.js. It is a native API in node.js. So, it is faster than other third-party libraries.

Advertisement

Cross-platform familiarity

The Fetch API is a standard API that is available in all modern browsers. So, if you are familiar with the Fetch API in the browser, you can use the same API in node.js. It is a cross-platform API.

Better performance

The Fetch API is a native API in node.js. So, it is faster than other third-party libraries.

Drawbacks of using the Fetch API in Node.js

Fetch API has some drawbacks too. It is not a complete replacement for the HTTP module. It is a high-level API. So, it is not suitable for all use cases. For example, if you want to make a request to a server with a self-signed certificate, you can't use fetch API. You need to use the HTTP module for this use case.

Error handling

The Fetch API doesn't provide any error handling. So, you need to handle errors manually. For example, if you want to handle a 404 error, you need to write the following code:

fetch('https://example.com/movies.json')
  .then((response) => {
    if (!response.ok) {
      throw new Error('Network response was not ok')
    }
    return response.json()
  })
  .then((data) => console.log(data))
  .catch((error) => console.error('There has been a problem with your fetch operation:', error))

Setting timeouts

The Fetch API doesn't provide any timeout option. So, you need to handle timeouts manually. For example, if you want to set a timeout of 10 seconds, you need to write the following code:

const controller = new AbortController()

const timeout = setTimeout(() => {
  controller.abort()
}, 10000)

fetch('https://example.com/movies.json', { signal: controller.signal })
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error('There has been a problem with your fetch operation:', error))
  .finally(() => clearTimeout(timeout))

No request progress events

Another major drawback of the Fetch API is that it doesn't provide any request progress events. So, you can't track the progress of a request. For example, if you want to track the progress of a request, you need to use the HTTP module.

Which node.js version supports fetch API?

Node.js v16.15.0 has been released with the fetch API as experimental. So, you need to enable the experimental flag to use fetch API in node.js. You can enable the experimental flag by setting the environment variable NODE_OPTIONS to --experimental-fetch.

From node.js v17.0.0, the fetch API will be enabled by default. So, you don't need to enable the experimental flag to use fetch API in node.js.

Conclusion

It is so exciting to see that the fetch API is now available in node.js. It may take a while (about a year or two) for the Fetch API to be fully stable in Node.js since there’s still a lot to do to make it standard-compliant. Many interesting updates are also set to happen in the near future, one of which includes adding HTTP/2 support to Undici, and eventually the Fetch API itself.

Thanks for reading this article. If you have any questions, please leave a comment below. If you like this article, please share it with your friends. You can also follow me on Twitter and GitHub

Advertisement