Making HTTP requests

Topic 4 of 4 in HTTP from scratch7 min readIntermediateFree course

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

JavaScript
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:

JavaScript
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:

JavaScript
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.

JavaScript
const res = await fetch(url);
const data = await res.json(); // ✗ if the server returned 500 with an HTML error page, this throws a confusing SyntaxError

fetch 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:

JavaScript
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:

JavaScript
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:

JavaScript
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.

Try 1 times out after 2 seconds; wait 0.5 s; try 2 gets a 503; wait 1 s; try 3 succeeds. Retry only temporary failures — timeouts, 429, 502 to 504 — and only safe requests, adding random jitter so thousands of clients don’t retry at the same instant.

Good retry rules:

  • Retry only temporary failures — network errors, timeouts, 429, 502, 503, 504. Never retry 400, 401, 403, 404 or 422 — the same request will fail the same way.
  • Retry only idempotent requests (GET, PUT, DELETE). Retrying a POST that 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-After when a 429 or 503 includes 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:

JavaScript
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:

JavaScript
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):

JavaScript
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:

JavaScript
// 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.

Exercise

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.

JavaScript
import { setTimeout as sleep } from 'node:timers/promises';

export async function getJson(url, { retries = 2, timeout = 3000 } = {}) {
  // your code here
}

Summary

  • fetch is built into Node; it resolves for any HTTP response and rejects only on network failure.
  • Always check res.ok (or res.status) and read the body once with json(), text() or arrayBuffer().
  • 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.