22-02-2022

Using fetch in Node

Recently released version 17.5 (opens new window) of Node.js introduced an experimental tag, --experimental-fetch. Doing so will install fetch related globals.

What is fetch? See the official mozilla documentation here (opens new window). It’s basically a set of interfaces that are related to fetching resources (usually through network calls). For example, with the fetch() method you are able to do an HTTP request to handle/consume the response.

A big benefit as a developer is that you will be working with the similar fetch api that you can use client-side in browsers. You can basically have shared code on bother client-side and server-side. Hopefully this brings a standardized HTTP client in the JS code space (no polyfilling necessary), boosting productivity.

To make use of fetch simply just mention the –experimental-fetch tag when running the node command.

node --experimental-fetch index.js

The great thing about is that you don’t need to do anything special as fetch is available as a global. You can then use it like so:

fetch("https://www.bobharing.com/")
	.then(response => response.text())
	.then(data => console.log(data));

If you look at the example code above more closely you can see that we also have access to the text() method. This is because we are dealing with the Response interface of the Fetch API. We also have access to other methods and properties such as json() and status(). The same also goes for the following interfaces Request and Headers too.

It’s important to note that under the hood that the fetch implementation is done based on another HTTP client, undici (opens new window), which is actually a HTTP client written specifically for Node.js. It is an HTTP 1.1 only client.

As the flag suggests, it is experimental. So use this on production environments at your own risk. Alternatives you can go for are now are node-fetch (opens new window) and axios (opens new window) (useable for both client and server side, isomorphic).

© 2024 Bob Haring