Skip to content

Lesson 9 of 14 · 25m

fetch(): Resolved Promises, Failed Requests

fetch fulfills on a 500 — res.ok is the check, and server-side fetch of user URLs is SSRF waiting to happen.

fetch resolves successfully on a 500. It rejects on DNS failures, connection refusals, CORS blocks, and aborts — and nothing else. Every 4xx and 5xx is a fulfilled promise whose response says the request failed. The single most common fetch bug in production is await fetch(url).then(r => r.json()) cheerfully parsing an HTML error page.

res.ok is the check that exists for a reason

const res = await fetch(url, { signal: AbortSignal.timeout(10_000) });
if (!res.ok) {
  throw new Error(`upstream ${res.status}: ${await res.text()}`);
}
const data = await res.json();

res.ok covers 200–299. If you need more than a boolean, switch on res.status — a 404 from a lookup API is often a legitimate "not found," while a 503 wants a retry path, not a stack trace. And res.json() throws on non-JSON bodies: check res.headers.get('content-type') when an upstream is flaky, because a CDN's text/html error page will throw a SyntaxError from inside json() and masquerade as a parse bug.

The body is single-use — res.bodyUsed flips true after the first read. Need it twice? res.clone() before consuming. And res.json() / res.text() / res.arrayBuffer() buffer the entire body in memory; for large payloads, stream res.body.getReader() or pipe it to disk instead of discovering your RAM ceiling on a log export.

Defaults that surprise

  • Redirects: redirect: 'follow' is default, up to 20 hops. redirect: 'manual' exposes the Location header — in browsers you get an opaqueredirect response you can't read; in Node you can.
  • Credentials: browser fetch sends cookies same-origin only by default — credentials: 'include' is required cross-origin (and the server must answer Access-Control-Allow-Credentials). Node's fetch (undici, global since Node 18) has no cookie jar at all — you manage Cookie headers yourself.
  • No timeout: there is no built-in timeout — that's what AbortSignal.timeout is for (the cancellation lesson).

Build URLs like they parse

const url = new URL('/api/users', base);
url.searchParams.set('q', query);        // encodes correctly
url.searchParams.set('page', String(page));

Never string-concatenate user input into a URL — searchParams.set handles percent-encoding, and new URL normalizes. encodeURIComponent exists for path segments, but if you're hand-assembling query strings you're already doing it wrong.

SSRF: the fetch you didn't mean to make

Server-side fetch of a user-supplied URL is the textbook server-side request forgery. The causal chain: attacker supplies a URL, your server fetches it with its network position and its credentials — and internal endpoints are now reachable from the public internet. The canonical example is the cloud metadata service at 169.254.169.254, which returns IAM credentials to anyone who asks — the mechanism behind the 2019 Capital One breach.

The correct practice, in order:

  1. Allowlist, don't denylist. Match new URL(input).hostname against a fixed set of expected hosts. Filtering "bad" hosts loses to DNS rebinding, decimal/octal IP encodings (2130706433 is 127.0.0.1), and redirects.
  2. Re-check after redirects. redirect: 'manual' and re-validate each hop's Location — the first URL passing your allowlist means nothing if it 302s to the metadata service.
  3. Resolve and pin. Check the resolved IP is public after DNS, and pin the connection to it — checking the hostname once and letting the HTTP client re-resolve is a TOCTOU race against an attacker-controlled TTL.

Try this

Point fetch at a URL that returns 500 with an HTML body. Observe that the promise fulfills, res.ok is false, and res.json() throws on the error page. Then add the res.ok guard, a content-type check, and an AbortSignal.timeout — and run it again against a delayed endpoint to watch the 'TimeoutError' arrive on schedule.

Field notes

  • fetch in browsers honors the page's CSP connect-src; in Node, nothing restricts it — your allowlist is the only boundary.
  • A 429 or 503 with Retry-After is an instruction, not just a status — read the header before hammering again.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.