Search code examples
node.jsreactjsnpm

Npm - fetch vs node-fetch?


These package names are pretty confusing, they seem like they do the same thing yet 'fetch' looks to be abandoned yet not marked as deprecated (last commit 3 years ago). Judging from the download counts people are probably downloading 'fetch' when they should get the supported and maintained 'node-fetch' package.

If you're building a Reactjs app, is fetch already built in? If so, is it different than 'node-fetch'?

What is the suggested package npm users should use?

https://www.npmjs.com/package/fetch

https://www.npmjs.com/package/node-fetch


Solution

  • Oct 2023

    The Fetch API has been marked as stable since Node 21, released Oct 2023.

    A bit of history

    Fetch is a standard created in 2015 by the Web Hypertext Application Technology Working Group (WHATWG). It was meant to replace the old and cumbersome XMLHttpRequest as means for issuing web requests. As it was meant to replace XMLHttpRequest the standard was clearly targeted at browsers rather than Node runtime, however due to it's wide adoption and for cross compatibility reasons, it was decided that it should also be implemented in Node.

    Nonetheless, it took Node team roughly 3 years to implement experimental fetch in Node v16. Although still experimental it is now enabled by default in Node v18.

    Because it took Node dev team so long to implement the Fetch standard, the community took matter in their own hands and created the node-fetch package which implements the Fetch standard.

    The fetch package that you have mentioned is just coincidentally named the same as the standard but it has nothing to do with it other than that they both aim to "fetch"/"request" resources from the web.

    What should you use?

    In the past browsers used XMLHttpRequest API and Node used its own http.request. We now have the opportunity to bring those two ecosystems closer still by having them both use the Fetch API. This increases code interoperability and even allows code sharing between the browser and Node in certain cases.

    Now, there are other popular packages out there such as axios or requests that still don't use Fetch under the hood but rather continue using Node's http library. Not using Fetch reduces inter-compatibility and therefore I don't think you should keep using either of them unless they convert, which is unlikely in the near future.

    Instead, you should consider using Node's native fetch or node-fetch package . Which one though? Well, my opinion is that the Node's fetch is still in early phases but given it has the support from the core Node team I would bet on that. I suppose node-fetch has a wider adoption of the Fetch standard but I think over time it will become redundant as the Node's native fetch becomes fully implemented.

    Please see the answer by 'Daniel Viglione' for a more detailed comparison between the node fetch API and the node-fetch package.