Making HTTP requests with fetch and undici

Intermediate · 24 min

Node's built-in fetch, why a 404 does not throw, timeouts and retries, and how undici's Agent and Pool reuse connections.

Before thisThe http module and building a serverCancellation with AbortController

JavaScript Conferences by GitNation · 24 min

Making HTTP requests with fetch and undici

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by JavaScript Conferences by GitNationReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Node has a global `fetch`, implemented by undici, an HTTP client built by the Node core team. No package is needed for ordinary requests.
  • `fetch` rejects only on network failure, timeout or abort. A 404 or 500 resolves normally, so check `response.ok` or `response.status` yourself.
  • Give every outbound request a deadline: `fetch(url, { signal: AbortSignal.timeout(ms) })`. By default a request can wait a long time.
  • Retry only what is safe: network errors, timeouts and 5xx on idempotent requests, with exponential backoff and jitter and a retry cap.
  • Connection reuse comes from the dispatcher. undici's `Agent` and `Pool` keep sockets alive, cap connections per origin, and set header and body timeouts, and `agent.compose(interceptors.retry(...))` adds retries.

fetch is already in Node

The browser’s fetch is a global in Node, so a JSON request needs no dependency:

const res = await fetch('https://api.example.com/items/1');
const item = await res.json();

Under the hood this is undici, a modern HTTP/1.1 client written by Node core contributors, bundled into Node (Node 26 reports undici 8.12 in process.versions.undici). The same package is on npm if you want its extra APIs or a newer version than your Node bundles.

The two traps: status and deadlines

First, fetch does not treat HTTP errors as errors. A 404 resolves:

const res = await fetch(base + '/missing');
console.log(res.ok, res.status, await res.json()); // false 404 { error: 'nope' }

A small wrapper makes the check hard to forget:

async function getJson(url, init) {
  const res = await fetch(url, { signal: AbortSignal.timeout(2000), ...init });
  if (!res.ok) throw Object.assign(new Error(`HTTP ${res.status}`), { status: res.status, body: await res.text() });
  return res.json();
}

Second, you should not rely on the defaults for deadlines. undici’s header and body timeouts are measured in minutes, and a stuck upstream ties up a socket and a request handler for that long. AbortSignal.timeout(2000) makes the call reject with a TimeoutError after 2 seconds (see cancellation). Also consume or cancel the response body: an unread body keeps the connection from returning to the pool.

Retries that do not make things worse

A retry helps with transient failures and hurts with permanent ones. The rules:

  • Retry network errors, timeouts and 5xx (especially 502, 503, 504).
  • Only for idempotent requests (GET, PUT, DELETE), or when the API supports an idempotency key. A retried POST /orders can create two orders.
  • Never retry 4xx. A 400 or 404 will fail again.
  • Back off exponentially, add jitter, and cap the attempts.
async function withRetry(fn, { retries = 3, baseMs = 100 } = {}) {
  for (let attempt = 0; ; attempt++) {
    try { return await fn(); }
    catch (err) {
      const retryable = err.status >= 500 || err.name === 'TimeoutError' || err.cause?.code === 'ECONNRESET';
      if (!retryable || attempt >= retries) throw err;
      await new Promise((r) => setTimeout(r, Math.random() * baseMs * 2 ** attempt));
    }
  }
}

const data = await withRetry(() => getJson('https://api.example.com/flaky'));

I ran this against a local server that returned 503 twice and then 200: it succeeded on the third attempt. Jitter matters because clients that fail together otherwise retry together.

Connections, Agents and Pools

Opening a TCP (and TLS) connection per request is slow, so undici keeps connections alive in a dispatcher. The global one is an Agent with sensible defaults. You can tune it with the npm package:

import { Agent, Pool, interceptors, fetch as ufetch } from 'undici';

const agent = new Agent({ keepAliveTimeout: 10_000, connections: 4, headersTimeout: 5000, bodyTimeout: 5000 });
const res = await ufetch('http://localhost:3412/', { dispatcher: agent });

const pool = new Pool('http://localhost:3412', { connections: 2 });
await Promise.all(Array.from({ length: 10 }, async () => {
  const { body } = await pool.request({ path: '/', method: 'GET' });
  await body.text();
}));
// the server saw 2 connections for 10 requests

const retrying = new Agent().compose(interceptors.retry({ maxRetries: 3, minTimeout: 10, statusCodes: [503], methods: ['GET'] }));

An Agent manages a pool per origin; a Pool is one origin with a connection cap. Use undici.request() for its leaner API when you do not need fetch’s browser-compatible shape. I ran all of this on Node 26 against undici 8; the retry interceptor turned two 503s into one successful response. One caution: pass a dispatcher from the npm undici to its own fetch; mixing it with the global fetch may fail when the bundled and installed versions differ.

What the video covers

This is Matteo Collina’s Node Congress 2024 talk, “Deep Dive into Undici”. Its description says undici is the next-generation HTTP client built by the Node.js core team that powers Node’s fetch(), and that the talk digs into its internals, Dispatchers, Agents and Pools, and ends with some “magic”. It is a talk by undici’s author about internals and connection management, so it matches the last section of this page best. I could not read a transcript. The status-check trap, deadlines, and retry guidance are this page’s.

Where this fits

Fetch is the client side of the http module, and responses are web streams. The browser view of the same API is in fetch and working with APIs. For the HTTP semantics of idempotency and retries across services, see API design.

Check yourself

  1. 01`const res = await fetch(url)` returns without throwing, but the server replied 404. How do you handle it?

    `fetch` only rejects when no response arrives. Check `res.ok` (true for 200 to 299) or `res.status`, and throw your own error carrying the status and, if useful, the body. A helper that wraps `fetch` and throws on `!res.ok` keeps this in one place.

  2. 02Which failures are safe to retry automatically?

    Network errors such as ECONNRESET, timeouts, and 502, 503 or 504 responses, when the request is idempotent (GET, PUT, DELETE) or carries an idempotency key. Do not retry POSTs that create things without a key, and do not retry 4xx errors, which will fail the same way.

  3. 03Why add random jitter to a retry delay?

    If many clients fail together and retry on the same schedule, they hit the recovering server at the same instant again. Randomising each delay, as in `Math.random() * base * 2 ** attempt`, spreads the load out so the server can recover.

  4. 04What does an undici `Pool` with `connections: 2` do when you fire 10 requests at once?

    It opens at most two connections to the origin and queues or pipelines the rest over them. In a test of ten parallel requests, the server saw exactly two connections opened. This bounds socket use and benefits from keep-alive reuse.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark