Skip to main content

Cloudsoft Zone Build, deploy and scale with practical guides to PHP, Node.js, React, DevOps and AI automation. Explore the guides

Cloudsoft Zone
Node.jsTutorial

Node.js fetch in production: timeouts, retries and errors

Make Node.js fetch() production-ready: check res.ok, add AbortSignal timeouts, read every body, retry the right failures and tune undici connection pools.

Nilesh Kushvaha

Updated 8 min read

Cloudsoft Zone cover: Node.js fetch in production: timeouts, retries and errors
Image: Cloudsoft Zone
In this article

Part 4 of 9

Node.js in production

All parts

The built-in fetch() in Node.js is stable and good enough for production HTTP calls, but three defaults catch almost everyone: it does not throw on 404 or 500 responses, it waits up to five minutes for a slow server, and it never retries. Add an explicit timeout with AbortSignal.timeout(), check res.ok, always read or cancel the body, and retry only failures that are safe to repeat.

Node.js fetch is stable for production but has three risky defaults. This tutorial sets a Node fetch timeout with AbortSignal.timeout(), checks res.ok, handles the body, and builds a tested Node.js fetch retry helper, then covers streaming downloads, connection pools and proxies.

This tutorial builds a small, tested fetchJson() helper that does all four, then covers streaming downloads, connection pools and proxies. Every snippet was run on Node.js 24.19.0 against a local test server; outputs are copied from those runs.

What you are actually using

Global fetch() has been available without a flag since Node.js 18.0.0 and stopped being experimental in 21.0.0. It is built on undici, an HTTP/1.1 client written for Node.js, and the version bundled with your runtime is in process.versions.undici:

Shell
$ node -p "process.versions.undici"
7.29.0

That matters for timeouts. undici's documented defaults are 300 seconds for headersTimeout and bodyTimeout and 10 seconds to connect. A server that accepts the connection and then stalls can therefore hold your request, and whatever user is waiting on it, for five minutes.

Rule 1: fetch does not throw on HTTP errors

A 404 or 503 is a successful fetch as far as the API is concerned. The promise resolves and you must check the status yourself:

JavaScript
const res = await fetch('http://127.0.0.1:3001/missing');
console.log(res.ok, res.status); // fetch does not throw on 404
Shell
$ node status.mjs
false 404

The promise rejects only when there is no HTTP response at all: DNS failure, refused connection, reset socket or an aborted request. Those arrive as a TypeError with the message "fetch failed" and the real reason in err.cause:

Shell
$ node refused.mjs
TypeError fetch failed ECONNREFUSED

Rule 2: always set a timeout

AbortSignal.timeout(ms) creates a signal that aborts after the given time. Pass it as signal and a stalled request rejects with a TimeoutError:

JavaScript
try {
  const res = await fetch('http://127.0.0.1:3001/slow', {
    signal: AbortSignal.timeout(1000),
  });
  console.log(await res.text());
} catch (err) {
  console.log(err.name, '-', err.message);
}
Shell
$ node timeout.mjs
TimeoutError - The operation was aborted due to timeout

The signal covers the whole operation, including reading the body, so it is a true end-to-end deadline. If the caller can also cancel, for example because the incoming request was closed, combine both signals with AbortSignal.any([...]). A cancellation from the caller rejects with an AbortError instead, which lets you tell the two apart.

Rule 3: always consume or cancel the body

The undici documentation is explicit: always read or cancel the response body, even for responses you do not care about. An unread body can keep its connection busy, and relying on garbage collection to release it can exhaust the connection pool and stall later requests. Call await res.text(), res.json() or res.body?.cancel() on every path, error paths included.

A production helper: timeouts, status checks and retries

Putting the rules together gives a helper you can share across a codebase. It applies a per-attempt timeout, honours a caller's signal, turns non-2xx responses into a typed error, reads the body on every path and retries a short list of transient failures with exponential backoff, respecting Retry-After when the server sends it.

JavaScript
// http.mjs
export class HttpError extends Error {
  constructor(res, body) {
    super(`HTTP ${res.status} for ${res.url}`);
    this.name = 'HttpError';
    this.status = res.status;
    this.body = body;
  }
}

const RETRYABLE = new Set([408, 429, 500, 502, 503, 504]);
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

export async function fetchJson(url, { timeoutMs = 5000, retries = 2, signal, ...init } = {}) {
  for (let attempt = 0; ; attempt++) {
    const signals = [AbortSignal.timeout(timeoutMs)];
    if (signal) signals.push(signal);
    try {
      const res = await fetch(url, { ...init, signal: AbortSignal.any(signals) });
      if (res.ok) return await res.json();

      const body = await res.text(); // always consume the body
      if (!RETRYABLE.has(res.status) || attempt >= retries) throw new HttpError(res, body);
      const retryAfter = Number(res.headers.get('retry-after'));
      await sleep(Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter * 1000 : 200 * 2 ** attempt);
    } catch (err) {
      const retryable = err.name === 'TimeoutError' || err.cause?.code === 'ECONNRESET';
      if (err instanceof HttpError || !retryable || attempt >= retries || signal?.aborted) throw err;
      await sleep(200 * 2 ** attempt);
    }
  }
}

Using it:

JavaScript
import { fetchJson, HttpError } from './http.mjs';

// a test endpoint that answers 503 with Retry-After: 1 twice, then 200
console.log(await fetchJson('http://127.0.0.1:3001/flaky'));

try {
  await fetchJson('http://127.0.0.1:3001/missing');
} catch (err) {
  if (err instanceof HttpError) console.log(err.message, err.status);
}

try {
  await fetchJson('http://127.0.0.1:3001/slow', { timeoutMs: 500, retries: 1 });
} catch (err) {
  console.log(err.name);
}
Shell
{ ok: true, url: '/flaky' }        # succeeded on the third attempt, after about 2 s
HTTP 404 for http://127.0.0.1:3001/missing 404
TimeoutError                       # two 500 ms attempts, then gave up

Which failures to retry

FailureHow it appearsRetry?
TimeoutTimeoutErrorYes, for idempotent requests
Caller cancelledAbortErrorNo
Connection resetTypeError, cause.code ECONNRESETYes, for idempotent requests
Connection refused or DNS failureTypeError, cause.code ECONNREFUSED or ENOTFOUNDUsually no; fail fast and alert
408, 429, 500, 502, 503, 504res.ok === falseYes, with backoff and Retry-After
400, 401, 403, 404, 422res.ok === falseNo; the request itself is wrong

Be careful with POST. Retrying a payment or order request after a timeout can create a duplicate, because the first attempt may have succeeded. Retry non-idempotent requests only when the API supports an idempotency key, and send the same key on every attempt.

Sending JSON

JavaScript
const res = await fetch('http://127.0.0.1:3001/orders', {
  method: 'POST',
  headers: { 'content-type': 'application/json' },
  body: JSON.stringify({ sku: 'A-100', quantity: 2 }),
  signal: AbortSignal.timeout(5000),
});
console.log(res.status, await res.json());

Set content-type yourself. When the body is a string, fetch labels it text/plain;charset=UTF-8 by default (we checked: a JSON string posted without the header arrived as text/plain), and many APIs reject that.

Streaming large downloads to disk

res.body is a web ReadableStream. Convert it with Readable.fromWeb() and use pipeline(), which handles backpressure and cleans up both streams on error, instead of buffering the whole file with arrayBuffer():

JavaScript
import { createWriteStream } from 'node:fs';
import { pipeline } from 'node:stream/promises';
import { Readable } from 'node:stream';

const res = await fetch('http://127.0.0.1:3001/download');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
await pipeline(Readable.fromWeb(res.body), createWriteStream('download.json'));
console.log('saved');

Connection pools and per-service limits

To set limits per upstream service, such as maximum sockets or shorter header timeouts, pass an undici dispatcher. The Node.js documentation lets you pass any undici-compatible dispatcher in the dispatcher option. The safest way to do this is to install undici and use its own fetch and Agent together, so both come from the same version; the npm release (8.x on 9 October 2026, which requires Node.js 22.19.0 or later) is newer than the 7.x copy inside Node.js 24.

JavaScript
import { fetch, Agent } from 'undici';

// one agent per upstream service, created once at start-up
const paymentsAgent = new Agent({
  connections: 20,          // max sockets per origin
  connectTimeout: 5_000,    // TCP + TLS handshake
  headersTimeout: 10_000,   // time to receive response headers
  bodyTimeout: 10_000,      // max idle time between body chunks
  keepAliveTimeout: 4_000,
});

const res = await fetch('https://payments.internal.example/health', {
  dispatcher: paymentsAgent,
});

When headersTimeout fires this way, the error is a TypeError with cause.code UND_ERR_HEADERS_TIMEOUT rather than a TimeoutError, so check for both in retry logic. The undici README also warns not to mix the global FormData with undici.fetch() or undici.FormData with the global fetch().

Corporate proxies

Node.js 24 can route fetch through the proxy in HTTP_PROXY, HTTPS_PROXY and NO_PROXY. Enable it with the NODE_USE_ENV_PROXY=1 environment variable (added in 24.0.0) or the --use-env-proxy flag (added in 24.5.0). Both are marked Stability 1.1, active development, so test them on your Node.js version before relying on them.

Shell
NODE_USE_ENV_PROXY=1 HTTPS_PROXY=http://proxy.internal:3128 node server.js

Gotchas

  • One timeout is not enough for retries. Create a new AbortSignal.timeout() for each attempt, and cap the total number of attempts so a retry loop cannot outlive the request that triggered it.
  • Do not log full error objects blindly. Request URLs and headers can contain tokens; log the status, method, host and cause.code.
  • Relative URLs do not work. There is no page origin on a server, so always pass absolute URLs, ideally built from configuration.
  • Response bodies can be large. Before calling res.json() on an untrusted service, check content-length or stream with a size limit.

What to do next

Search your codebase for fetch( and check each call for three things: a timeout signal, a status check and a body that is read on every path. Move the calls into one shared helper like fetchJson() so the policy lives in a single place, and add metrics for attempts, retries and timeouts per upstream host. Those numbers will tell you which dependency to talk to before your users do.

Frequently asked questions

  • Is fetch stable in Node.js?

    Yes. It has been available without a flag since Node.js 18.0.0 and was marked no longer experimental in 21.0.0. It is built on the undici HTTP client.

  • What is the default timeout for fetch in Node.js?

    There is no overall deadline. undici's defaults are 300 seconds to receive headers, 300 seconds of idle time while reading the body and 10 seconds to connect. Set your own with AbortSignal.timeout().

  • Why does fetch not throw on a 404 or 500?

    Because the request succeeded at the HTTP level. Check res.ok or res.status yourself. fetch() only rejects when no response was received, for example on a refused connection, a timeout or an abort.

  • How do I tell a timeout from a cancellation?

    A signal from AbortSignal.timeout() rejects with an error named TimeoutError; a manual AbortController.abort() rejects with AbortError.

  • Do I still need axios or node-fetch?

    Not for most server code. The built-in fetch() covers JSON APIs, streaming and cancellation. You still need your own helper for timeouts, status checks and retries, which is a few dozen lines.

  • How do I make fetch use a proxy in Node.js?

    On Node.js 24, set NODE_USE_ENV_PROXY=1 or start with --use-env-proxy, and Node.js will honour HTTP_PROXY, HTTPS_PROXY and NO_PROXY. The feature is still marked as in active development.

Sources

  1. Global objects: fetch (Node.js v24 docs) — Node.js
  2. Command-line options: NODE_USE_ENV_PROXY and --use-env-proxy (Node.js v24 docs) — Node.js
  3. undici README — Node.js / undici
  4. undici Client API — Node.js / undici
  5. undici on npm — npm

Part 5 of 9: Node.js in production

Previous part
Cloudsoft Zone cover: Node.js production security checklist

Resource guideNode.js8 min read

Node.js production security checklist for 2026

A practical security checklist for Node.js APIs and web apps: supported versions, npm supply-chain controls, secrets, HTTP timeouts, prototype pollution, constant-time comparisons and the Permission Model.

Comments

No comments yet. Be the first to join the conversation.

Leave a comment

Every comment is read by a moderator before it appears. Your email address is never published; it is used only to contact you about this comment.

Never published. Used only to contact you about this comment.

Loading the security check…

Comments are moderated before publication.