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.
_10const response = await fetch('https://api.example.com/users/1');_10_10if (!response.ok) {_10 throw new Error(`Request failed: ${response.status}`);_10}_10_10const 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.
_10const url = new URL('https://api.example.com/search');_10url.searchParams.set('q', 'node fetch');_10url.searchParams.set('limit', '10');_10_10const response = await fetch(url, {_10 headers: { Accept: 'application/json' },_10});_10const 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.
_14const 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_14if (!response.ok) {_14 throw new Error(`Request failed: ${response.status} ${await response.text()}`);_14}_14_14const created = await response.json();
Add a timeout
Pass AbortSignal.timeout() as the signal. If the request takes too long, it rejects with a TimeoutError.
_12try {_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.
_15export 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
_10import { openAsBlob } from 'node:fs';_10_10const form = new FormData();_10form.append('file', await openAsBlob('report.pdf'), 'report.pdf');_10_10await 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
404throws. Always checkresponse.okorresponse.status. - Reading the body twice.
response.json()andresponse.text()can only be called once; useresponse.clone()if you need both. - Forgetting
JSON.stringifyon 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
fetchhas no cookie jar; pass theCookieheader yourself.
Related reading
#Was this resource helpful?