More Node.js answers

by Danny
Published 2 min read

Node has a built-in fetch, so most projects no longer need axios. Learn how to send GET and POST requests, handle errors and status codes, and add timeouts.

The short answer

#

Use the global fetch. It is built into Node, stable since Node 21 and available in every supported release, with no package to install. It works the same way as fetch in the browser.


_10
const response = await fetch('https://api.example.com/users/1');
_10
_10
if (!response.ok) {
_10
throw new Error(`Request failed: ${response.status}`);
_10
}
_10
_10
const user = await response.json();

Why it happens

#

For years Node only had the low-level http and https modules, which need a lot of code for a simple request. Libraries such as axios and node-fetch filled that gap. Node now ships its own fetch, powered by the undici HTTP client, along with Request, Response, Headers, FormData and AbortController.

The main difference from axios is how errors work. fetch only rejects when the request cannot be made at all, for example a DNS failure or a refused connection. A 404 or 500 response is still a successful promise, so you have to check response.ok yourself. It also does not parse JSON or set a timeout for you.

How to fix it

#

Send a GET request with query parameters

Build the URL with URL and URLSearchParams so values are encoded correctly.


_10
const url = new URL('https://api.example.com/search');
_10
url.searchParams.set('q', 'node fetch');
_10
url.searchParams.set('limit', '10');
_10
_10
const response = await fetch(url, {
_10
headers: { Accept: 'application/json' },
_10
});
_10
const results = await response.json();

Send JSON in a POST request

Set the method, a Content-Type header, and a body made with JSON.stringify. axios does this conversion for you; fetch does not.


_14
const response = await fetch('https://api.example.com/users', {
_14
method: 'POST',
_14
headers: {
_14
'Content-Type': 'application/json',
_14
Authorization: `Bearer ${process.env.API_TOKEN}`,
_14
},
_14
body: JSON.stringify({ name: 'Ada', role: 'admin' }),
_14
});
_14
_14
if (!response.ok) {
_14
throw new Error(`Request failed: ${response.status} ${await response.text()}`);
_14
}
_14
_14
const created = await response.json();

Add a timeout

Pass AbortSignal.timeout() as the signal. If the request takes too long, it rejects with a TimeoutError.


_12
try {
_12
const response = await fetch('https://api.example.com/slow', {
_12
signal: AbortSignal.timeout(5000),
_12
});
_12
console.log(await response.json());
_12
} catch (error) {
_12
if (error.name === 'TimeoutError') {
_12
console.error('Request took longer than 5 seconds');
_12
} else {
_12
throw error;
_12
}
_12
}

Wrap it in a small helper

If you liked axios because it threw on error status codes and parsed JSON, a few lines give you the same behaviour.


_15
export async function getJson(url, options = {}) {
_15
const response = await fetch(url, {
_15
...options,
_15
signal: options.signal ?? AbortSignal.timeout(10_000),
_15
headers: { Accept: 'application/json', ...options.headers },
_15
});
_15
_15
if (!response.ok) {
_15
const error = new Error(`HTTP ${response.status} for ${url}`);
_15
error.status = response.status;
_15
throw error;
_15
}
_15
_15
return response.json();
_15
}

Upload files with FormData


_10
import { openAsBlob } from 'node:fs';
_10
_10
const form = new FormData();
_10
form.append('file', await openAsBlob('report.pdf'), 'report.pdf');
_10
_10
await fetch('https://api.example.com/upload', { method: 'POST', body: form });

Do not set Content-Type yourself here. fetch adds the correct multipart boundary.

Common pitfalls

#
  • Assuming a 404 throws. Always check response.ok or response.status.
  • Reading the body twice. response.json() and response.text() can only be called once; use response.clone() if you need both.
  • Forgetting JSON.stringify on the body, which sends the text [object Object].
  • Not reading or cancelling the body of responses you ignore. Unread bodies can keep connections open; call await response.body?.cancel() if you do not need it.
  • Expecting cookies to be kept between requests. Node's fetch has no cookie jar; pass the Cookie header yourself.
#

Was this resource helpful?