Making HTTP requests
Overview
Back ends rarely work alone. Your API might call a payment provider, send email through a mail service, fetch exchange rates, verify a captcha or talk to another of your own services. That means your server is also an HTTP client.
Node has the same fetch you know from the browser built in (it’s powered by a library called Undici). This topic covers using it robustly — because every external service is sometimes slow, sometimes down, and sometimes returns something unexpected.
The basics
const res = await fetch('https://api.github.com/repos/nodejs/node');
console.log(res.status); // 200
console.log(res.headers.get('content-type')); // 'application/json; charset=utf-8'
const repo = await res.json();
console.log(repo.stargazers_count);Sending JSON:
const res = await fetch('https://api.example.com/orders', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.ORDERS_API_KEY}`,
},
body: JSON.stringify({ productId: 'p_123', quantity: 2 }),
});Building a URL with query parameters safely:
const url = new URL('https://api.example.com/search');
url.searchParams.set('q', 'node streams');
url.searchParams.set('limit', '20');
const res = await fetch(url);Checking responses
The most common fetch bug: assuming success.
const res = await fetch(url);
const data = await res.json(); // ✗ if the server returned 500 with an HTML error page, this throws a confusing SyntaxErrorfetch only rejects when no response arrived (DNS failure, connection refused, timeout, abort). A 404 or 500 is still a response, so the promise resolves. Check it:
const res = await fetch(url);
if (!res.ok) {
const detail = await res.text();
throw new Error(`Payments API returned ${res.status}: ${detail.slice(0, 200)}`);
}
const data = await res.json();res.ok is true for status 200–299. A response body can only be read once — choose json(), text(), arrayBuffer() or blob(), or stream it with res.body.
Timeouts
By default, a request to an unresponsive server can hang for a long time — and while it hangs, your user’s request hangs too. Set a timeout on every outgoing call:
try {
const res = await fetch(url, { signal: AbortSignal.timeout(3000) });
} catch (err) {
if (err.name === 'TimeoutError') {
// the service took longer than 3 seconds
}
throw err;
}Choose timeouts based on what the user can tolerate. If your endpoint should answer within 2 seconds, a 30-second timeout on a dependency is meaningless.
To cancel when either a timeout passes or the incoming request is aborted, combine signals:
const signal = AbortSignal.any([AbortSignal.timeout(3000), userAbortController.signal]);Retries with backoff
Some failures are temporary: a brief network blip, a server restarting (503), an overloaded gateway (502, 504), or rate limiting (429). Retrying after a short pause often succeeds.
Good retry rules:
- Retry only temporary failures — network errors, timeouts,
429,502,503,504. Never retry400,401,403,404or422— the same request will fail the same way. - Retry only idempotent requests (
GET,PUT,DELETE). Retrying aPOSTthat charged a card might charge it twice — unless the API supports idempotency keys (a unique header value that lets the server recognise a repeat). - Back off exponentially — wait 0.5 s, then 1 s, then 2 s — so a struggling service gets room to recover.
- Add jitter — a little randomness, so thousands of clients don’t all retry at the same moment.
- Respect
Retry-Afterwhen a429or503includes it. - Cap the attempts — two or three retries is usually plenty.
The exercise for this topic builds exactly this helper.
Many requests at once
To fetch several independent things, run them in parallel:
const [user, orders] = await Promise.all([
getJson(`${USERS_API}/users/${id}`),
getJson(`${ORDERS_API}/orders?user=${id}`),
]);But firing 5,000 requests at once can overwhelm the other service (and get you rate-limited). Process big lists with a concurrency limit:
async function mapWithLimit(items, limit, fn) {
const results = new Array(items.length);
let next = 0;
async function worker() {
while (next < items.length) {
const i = next++;
results[i] = await fn(items[i]);
}
}
await Promise.all(Array.from({ length: limit }, worker));
return results;
}
const profiles = await mapWithLimit(userIds, 5, (id) => getJson(`${API}/users/${id}`));Packages such as p-limit provide the same thing ready-made.
Streaming responses
For large downloads, don’t buffer the whole body — stream it to disk (see Piping and pipeline):
import { Readable } from 'node:stream';
await pipeline(Readable.fromWeb(res.body), createWriteStream('export.zip'));Wrap each external service
Rather than scattering fetch calls everywhere, give each external service a small module with clear functions:
// services/rates.js
const BASE = 'https://api.rates.example.com';
export async function getRate(from, to) {
const data = await getJson(`${BASE}/latest?from=${from}&to=${to}`, { timeout: 2000 });
return data.rates[to];
}This keeps API keys, URLs, timeouts and error handling in one place, and makes the service easy to replace with a fake in tests (see Mocking and test doubles).
Keep secrets on the server. One big reason to call third-party APIs from your back end, not the browser, is that API keys in front-end code are visible to everyone. Your Node server can hold the key and expose only the data the front end needs.
A resilient API client
Write getJson(url, { retries = 2, timeout = 3000 }) that fetches JSON with a timeout, throws on non-2xx responses, and retries timeouts, network errors and 502/503/504 responses with exponential backoff (500 ms, 1000 ms…). Don't retry 4xx errors.
import { setTimeout as sleep } from 'node:timers/promises';
export async function getJson(url, { retries = 2, timeout = 3000 } = {}) {
// your code here
}import { setTimeout as sleep } from 'node:timers/promises';
const RETRYABLE = new Set([502, 503, 504]);
export async function getJson(url, { retries = 2, timeout = 3000 } = {}) {
for (let attempt = 0; ; attempt++) {
try {
const res = await fetch(url, { signal: AbortSignal.timeout(timeout) });
if (res.ok) return await res.json();
const err = new Error(`HTTP ${res.status} from ${url}`);
err.status = res.status;
throw err;
} catch (err) {
const retryable = !err.status || RETRYABLE.has(err.status);
if (!retryable || attempt >= retries) throw err;
await sleep(500 * 2 ** attempt + Math.random() * 100);
}
}
}Summary
fetchis built into Node; it resolves for any HTTP response and rejects only on network failure.- Always check
res.ok(orres.status) and read the body once withjson(),text()orarrayBuffer(). - Set a timeout on every outgoing request with
AbortSignal.timeout(). - Retry only temporary failures, with exponential backoff and jitter, and only idempotent requests.
- Limit concurrency when making many requests; keep API keys on the server.