skip to content

In Node.js 24, how does the global fetch() differ from http.request() in its implementation, connection pooling and configuration?

level: middleimportance: must knowfreq 65%

answer

  1. two separate client stacks
  2. bundled library, not node:http
  3. dispatcher versus http.Agent
  4. which global settings reach which client

basics

~20 s

Node 24's global fetch() runs on the bundled undici client, not on node:http, so it pools connections in undici's global dispatcher and ignores http.Agent and http.globalAgent; http.request() is the lower-level, stream-based client those agents configure.

solid answer

~40 s

`fetch()` is the WHATWG API implemented by undici, a client Node bundles (`process.versions.undici` shows which version) and which was written from scratch rather than on top of `node:http`. Its connections live in undici's global dispatcher, an `Agent` that keeps one pool per origin with no connection cap by default; you change that per call with the non-standard `dispatcher` option or for the whole process with `setGlobalDispatcher()`; the dispatcher objects usually come from the npm `undici` package. `http.request()` returns a writable `ClientRequest`, hands you an `IncomingMessage` stream on `'response'`, and pools through an `http.Agent`, by default `http.globalAgent` (keep-alive on, 5-second socket timeout). Settings made on one stack never reach the other. `fetch()` also follows up to 20 redirects and resolves for any HTTP status; `http.request()` follows none and reports failures as `'error'` events.

code

javascript · 14 lines
javascript
import http from 'node:http';

// fetch(): pooled by undici's global dispatcher
const res = await fetch('http://localhost:3000/stock/42');
console.log(res.status, await res.json());

// http.request(): pooled by the agent you pass (or http.globalAgent)
const agent = new http.Agent({ keepAlive: true, maxSockets: 20 });
http.get('http://localhost:3000/stock/42', { agent }, (incoming) => {
  let body = '';
  incoming.setEncoding('utf8');
  incoming.on('data', (chunk) => { body += chunk; });
  incoming.on('end', () => console.log(incoming.statusCode, JSON.parse(body)));
}).on('error', console.error);

go deeper

for a junior

Recall that fetch() is global in Node 24 and resolves for any status, while http.request() is the older stream-and-event client from node:http.

for a middle

Explain that fetch() runs on bundled undici with its own dispatcher, http.request() runs on http.Agent, and neither one's pool settings reach the other.

for a senior

Show you can predict which pool a call lands in, how to cap or proxy each client, and why a setting that fixed one client changed nothing for the other.

for a principal

Weigh standardising on one client per service against mixing both, including the cost of depending on the npm undici package to configure fetch.

## Two HTTP clients inside one runtime A Node.js 24 process ships **two independent outbound HTTP clients**, and most confusion about connection reuse comes from treating them as one. - **`fetch()`** is a global, browser-compatible function. Its implementation is **undici**, an HTTP/1.1 client written from scratch for Node and bundled into the binary. `process.versions.undici` reports the bundled version. - **`http.request()`** (and `http.get()`, plus their `node:https` twins) is the original core client. It is built on `node:net` sockets, and it exposes requests and responses as streams and events. Neither one is a wrapper around the other. A tuning change, a proxy setting or a pool limit applied to one client has no effect on the other unless Node itself wires both, as the built-in proxy support does. ## fetch(): undici behind a web-standard API `fetch(url, init)` returns a promise for a `Response`. The important runtime facts: - **Pooling lives in a dispatcher.** undici keeps a process-wide global dispatcher: an `Agent` that creates one `Pool` per origin. A `Pool`'s `connections` option defaults to `null`, meaning no cap on connections per origin. - **Configuration goes through undici objects.** The non-standard `dispatcher` field in `init` takes any undici-compatible dispatcher for one call, and `setGlobalDispatcher()` from the npm `undici` package replaces the process-wide one. Node's documentation points to installing that package for this, so tuning fetch usually means adding it as a dependency. - **Failure model.** The promise resolves for every HTTP status, including 4xx and 5xx. It rejects on abort with the signal's reason, and on a network failure with `TypeError: fetch failed` whose `cause` carries undici's error, such as a connect or headers timeout. - **Redirects** are followed by default (`redirect: 'follow'`), up to 20 hops. - **Bodies are web streams.** `res.body` is a `ReadableStream`; `res.json()`, `res.text()` and `res.arrayBuffer()` consume it. ## http.request(): the stream-and-event client `http.request(url, options, callback)` returns a `ClientRequest`, a writable stream for the request body. The response arrives as an `IncomingMessage`, a Node `Readable`, on the `'response'` event. - **Pooling lives in an `http.Agent`.** With no `agent` option, the request uses `http.globalAgent`, which since v19 has `keepAlive` enabled and a 5-second socket `timeout`. `agent: false` gives the request a throwaway agent with default options. - **No automatic redirects.** A 301 or 302 is just a response with a `statusCode`; following it is your code's job. - **Errors are events.** Connection failures surface as an `'error'` event on the request, for example `socket hang up` with code `ECONNRESET`. - **Fine-grained hooks.** Options such as `lookup`, `family`, `localAddress`, `createConnection` and `socketPath` reach the socket layer directly. ## Where each client's settings live | Concern | `fetch()` | `http.request()` | |---|---|---| | Implementation | bundled undici | `node:http` core client | | Default pool | undici global dispatcher | `http.globalAgent` | | Per-call pool | `dispatcher` option | `agent` option | | Default per-origin cap | unlimited (`connections: null`) | unlimited (`maxSockets: Infinity`) | | Redirects | followed, up to 20 | never followed | | Body type | web `ReadableStream` | Node `Readable` | ## Errors look different The two clients report the same network failure in different shapes, which matters for logging and alerting: - **`fetch()`** rejects with `TypeError: fetch failed`. The useful detail is in `err.cause`: a system error with a code such as `ECONNREFUSED`, or one of undici's own errors with a code such as `UND_ERR_CONNECT_TIMEOUT`. Logging only `err.message` hides every root cause behind one string. - **`http.request()`** emits `'error'` on the `ClientRequest`, and the error carries `err.code` directly, for example `ECONNRESET` for `socket hang up`. Because `ClientRequest` is an `EventEmitter`, an `'error'` with no listener is thrown and can crash the process, so every request needs an `'error'` handler. ## Choosing between them 1. Use **`fetch()`** when the standard API is enough: portable code, promise-based flow, JSON in and out. 2. Use **`http.request()`** when you need socket-level options, a Node `Readable` without conversion, or an existing `http.Agent` setup. 3. Use the npm **`undici`** package directly when you want fetch's engine with explicit pools, its lower-level `request()` API, or a version newer than the bundled one. Installing it does not replace the global `fetch` unless you call its `install()` function. ## Mistakes that show up in production - Setting `http.globalAgent.maxSockets` and expecting it to cap `fetch()` traffic. The Node guide on enterprise networking states it directly: global agents do not affect `fetch()`. - Mixing implementations, such as the npm package's `FormData` with the built-in `fetch`; undici's documentation asks you to keep matching pairs. - Assuming a rejected fetch promise means a 5xx. A 503 resolves; only network failures and aborts reject.

  • If you set http.globalAgent = new http.Agent({ maxSockets: 10 }), does that cap the connections fetch() opens?
    No. `fetch()` sends through undici's dispatcher, not through `node:http` agents, and Node's own networking guide notes that global agents do not affect `fetch()`. To cap fetch, pass an undici `Agent` created with `connections: 10` in the `dispatcher` option, or install it process-wide with `setGlobalDispatcher()` from the npm `undici` package.
  • Why would a team check process.versions.undici before filing a fetch bug against Node?
    Because `fetch()` behaviour is undici's, and the bundled undici version moves with Node releases. A fix may already exist in a newer undici; the npm package can be imported directly, or installed as the globals with its `install()` function, without waiting for a Node upgrade.

  • fetch in Node is a thin wrapper over http.request and http.globalAgent.
  • Tuning http.globalAgent also tunes the connections fetch uses.
  • http.request follows redirects automatically, just like fetch.
  • A fetch promise rejects when the server answers 500.
  • Node 24 still needs --experimental-fetch before fetch can be used.

Assumes Node 24: fetch lost its --experimental-fetch flag in v18 and its experimental status in v21, and http.globalAgent has kept connections alive by default since v19.