Fetch API in Node
For years Node developers installed packages like axios or node-fetch just to make an HTTP request. Since Node 18 the browser's fetch() is built in and stable, so the same code works in the browser and on the server. It is powered by Undici, a fast HTTP client maintained by the Node team.
Note: The examples below start a tiny local server first and then fetch from it, so they work without internet access. In your own projects you would simply call a real URL such as
https://api.github.com/....
A first request
fetch(url) returns a promise that resolves to a Response as soon as the headers arrive. Reading the body is a second asynchronous step:
const http = require('node:http');
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ id: 7, title: 'Learn fetch', done: false }));
});
server.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
const response = await fetch(`${base}/todos/7`);
console.log('status:', response.status, response.statusText);
console.log('ok:', response.ok);
console.log('type:', response.headers.get('content-type'));
const todo = await response.json();
console.log(todo.title, '->', todo.done ? 'done' : 'open');
server.close();
});status: 200 OK
ok: true
type: application/json
Learn fetch -> open
Reading the body
A body can be read once, with one of these methods:
| Method | Resolves to |
|---|---|
response.json() |
parsed JSON value |
response.text() |
string |
response.arrayBuffer() |
raw bytes (ArrayBuffer) |
response.blob() |
Blob |
response.formData() |
FormData |
response.body |
a web ReadableStream for streaming large bodies |
Calling .json() and then .text() on the same response throws TypeError: Body is unusable. If you need it twice, call response.clone() first.
Sending data: POST with JSON
Pass an options object as the second argument. For JSON you set the method, a Content-Type header and a string body:
const http = require('node:http');
const server = http.createServer(async (req, res) => {
let raw = '';
for await (const chunk of req) raw += chunk;
const data = JSON.parse(raw);
res.statusCode = 201;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ received: data, method: req.method, type: req.headers['content-type'] }));
});
server.listen(0, async () => {
const url = `http://localhost:${server.address().port}/users`;
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Linh', role: 'admin' }),
});
console.log(res.status);
console.log(await res.json());
server.close();
});201
{
received: { name: 'Linh', role: 'admin' },
method: 'POST',
type: 'application/json'
}
Tip:
URLSearchParamsandFormDataobjects can be passed directly asbody; fetch then sets the rightContent-Typefor you.
Errors: fetch does not throw on 404
This surprises almost everyone: fetch only rejects on network failures (DNS error, refused connection, aborted request). A 404 or 500 is still a successful HTTP exchange, so you must check response.ok yourself:
const http = require('node:http');
const server = http.createServer((req, res) => {
if (req.url === '/missing') {
res.statusCode = 404;
return res.end('Not found');
}
res.end('fine');
});
async function getText(url) {
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status} for ${new URL(url).pathname}`);
return res.text();
}
server.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
for (const path of ['/hello', '/missing']) {
try {
console.log('got:', await getText(base + path));
} catch (err) {
console.log('error:', err.message);
}
}
server.close();
try {
await fetch(base + '/hello'); // server is closed now
} catch (err) {
console.log('network error:', err.name, '-', err.message);
}
});got: fine
error: HTTP 404 for /missing
network error: TypeError - fetch failed
Timeouts and cancellation
Fetch has no timeout option. Instead you pass an AbortSignal. AbortSignal.timeout(ms) creates one that aborts automatically:
const http = require('node:http');
const server = http.createServer((req, res) => {
setTimeout(() => res.end('finally!'), 500); // a slow endpoint
});
server.listen(0, async () => {
const url = `http://localhost:${server.address().port}/slow`;
try {
await fetch(url, { signal: AbortSignal.timeout(50) });
} catch (err) {
console.log('aborted:', err.name);
}
const res = await fetch(url, { signal: AbortSignal.timeout(2000) });
console.log('with more time:', await res.text());
server.closeAllConnections();
server.close();
});aborted: TimeoutError
with more time: finally!
For a manual "Cancel" button, create an AbortController, pass controller.signal, and call controller.abort() when needed — the rejected error is then named AbortError.
Quick reference
| Option | Example |
|---|---|
method |
'GET' (default), 'POST', 'PUT', 'PATCH', 'DELETE' |
headers |
{ Authorization: 'Bearer abc' } or a Headers object |
body |
string, URLSearchParams, FormData, Blob, buffer, stream |
signal |
AbortSignal.timeout(5000) |
redirect |
'follow' (default), 'manual', 'error' |
Test yourself
What happens when fetch() receives a 404 response?
- The promise rejects with a
NotFoundError - The promise resolves;
response.okisfalse - It retries automatically
- It returns
null
How do you give a fetch request a 3-second timeout?
fetch(url, { timeout: 3000 })fetch(url, { signal: AbortSignal.timeout(3000) })fetch.timeout = 3000setTimeout(fetch, 3000)
Since which Node version is fetch available globally and stable?
- Node 10
- Node 14
- Node 18 (stable since 21)
- Only with the
node-fetchpackage