Full answer
Since Node 18, fetch is a global function, and it is stable in current versions. It is implemented by undici and follows the browser API, so the same code runs on the server and in the browser.
Key behaviours:
- fetch(url, options) returns a promise of a Response. It rejects (TypeError: fetch failed, with a cause such as ECONNREFUSED) when the request could not be made. A 404 or 500 is a normal resolved response. Check response.ok or response.status.
- Reading the body: await response.json(), text(), arrayBuffer(), blob() or formData(). The body can be consumed once. Use response.clone() if you need two reads.
- Streaming: response.body is a web ReadableStream. for await (const chunk of response.body) works, and Readable.fromWeb(response.body) converts it to a Node stream.
- Sending: method, headers and body. For JSON: body: JSON.stringify(data) and a Content-Type: application/json header (fetch does not add it for strings). FormData and URLSearchParams set their own content type.
- Timeouts and cancellation: signal: AbortSignal.timeout(5000). Without it a hung server can wait for a long time (the default header timeout is 5 minutes in undici).
- Redirects are followed by default (redirect: 'follow'). Use 'manual' to inspect them, for example in SSRF protection.
- Cookies are not stored (no cookie jar), and there is no CORS in Node.
- Errors: add the URL and the status to the error you throw, and avoid logging full headers (they may contain tokens).
A small wrapper that sets a timeout, checks ok, and parses JSON with a clear error type removes most mistakes.
const http = require('node:http');
const server = http.createServer((req, res) => {
if (req.url === '/marks/1') {
res.setHeader('Content-Type', 'application/json');
return res.end(JSON.stringify({ id: 1, marks: 78 }));
}
if (req.url === '/slow') return; // never answers
if (req.method === 'POST') {
let body = '';
req.on('data', (c) => (body += c));
return req.on('end', () => res.end(JSON.stringify({ receivedType: req.headers['content-type'], body })));
}
res.statusCode = 404;
res.end('no such route');
});
async function getJson(url, options = {}) {
const response = await fetch(url, { signal: AbortSignal.timeout(100), ...options });
if (!response.ok) throw new Error(`HTTP ${response.status} for ${new URL(url).pathname}`);
return response.json();
}
server.listen(0, '127.0.0.1', async () => {
const base = 'http://127.0.0.1:' + server.address().port;
// A port where nothing listens: open a server, note its port, close it again.
const probe = require('node:net').createServer();
await new Promise((resolve) => probe.listen(0, '127.0.0.1', resolve));
const closedUrl = 'http://127.0.0.1:' + probe.address().port + '/';
await new Promise((resolve) => probe.close(resolve));
console.log('GET json:', await getJson(base + '/marks/1'));
const missing = await fetch(base + '/nope'); // resolves, even though it is a 404
console.log('404 does not reject: ok =', missing.ok, '| status =', missing.status, '| text =', await missing.text());
await getJson(base + '/nope').catch((err) => console.log('wrapper throws:', err.message));
await getJson(base + '/slow').catch((err) => console.log('slow server:', err.name));
await fetch(closedUrl).catch((err) => console.log('connection refused:', err.name + ':', err.message, '| cause code:', err.cause?.code ?? err.cause?.errors?.[0]?.code));
const res = await fetch(base + '/marks/1');
await res.text();
await res.text().catch((err) => console.log('second read:', err.name));
const post = await fetch(base, { method: 'POST', body: JSON.stringify({ name: 'Asha' }), headers: { 'Content-Type': 'application/json' } });
console.log('POST echo:', await post.json());
const noHeader = await fetch(base, { method: 'POST', body: JSON.stringify({ name: 'Asha' }) });
console.log('content type when the header is missing:', (await noHeader.json()).receivedType);
server.closeAllConnections();
server.close();
});The server never answers /slow, so the 100 ms timeout fires. A port where no server listens refuses the connection, which shows the other kind of failure. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): GET json: { id: 1, marks: 78 } 404 does not reject: ok = false | status = 404 | text = no such route wrapper throws: HTTP 404 for /nope slow server: TimeoutError connection refused: TypeError: fetch failed | cause code: ECONNREFUSED second read: TypeError POST echo: { receivedType: 'application/json', body: '{"name":"Asha"}' } content type when the header is missing: text/plain;charset=UTF-8
Key points
- fetch rejects on network failure, not on 404 or 500.
- Check response.ok.
- The body can be read once.
- Set a timeout with AbortSignal.timeout.
- JSON requests need the Content-Type header.
Common mistakes
- Assuming a 404 or 500 makes fetch reject.
- Calling response.json() twice.
- Posting JSON without the Content-Type header.
- Using fetch without any timeout.
Follow-ups
- How would you add retries to fetch?
- How do you stream a large download to a file?
- Why does the built-in fetch not send cookies automatically?
Tips
- Lead with 'fetch resolves for 404'.
- Mention AbortSignal.timeout.
- Add that undici is the engine behind it.