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 theLocationheader — in browsers you get anopaqueredirectresponse you can't read; in Node you can. - Credentials: browser
fetchsends cookies same-origin only by default —credentials: 'include'is required cross-origin (and the server must answerAccess-Control-Allow-Credentials). Node'sfetch(undici, global since Node 18) has no cookie jar at all — you manageCookieheaders yourself. - No timeout: there is no built-in timeout — that's what
AbortSignal.timeoutis 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:
- Allowlist, don't denylist. Match
new URL(input).hostnameagainst a fixed set of expected hosts. Filtering "bad" hosts loses to DNS rebinding, decimal/octal IP encodings (2130706433is127.0.0.1), and redirects. - Re-check after redirects.
redirect: 'manual'and re-validate each hop'sLocation— the first URL passing your allowlist means nothing if it 302s to the metadata service. - 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
fetchin browsers honors the page's CSPconnect-src; in Node, nothing restricts it — your allowlist is the only boundary.- A
429or503withRetry-Afteris an instruction, not just a status — read the header before hammering again.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
Angular 18: Deferred Views & Built-in Control Flow
The newest release of Angular – which is Angular 18 – is planned to be released on May 22nd, 2024. This is Google's super popular TypeScript based webapp framework that allows developers to create amazing web applications. The features, changes, and goodies of this release are deferrable views…
Angular 15: Simplifies Development Promises
Angular 15, a planned upgrade to Google’s TypeScript framework for web development, will stabilize standalone component APIs, simplifying application building, and offer a new way to compose UI logic, the company announced. Angular 15 is expected to arrive in November, said Minko Gechev, Google…
Angular 14 is Now Released
Angular 14, the latest version of the Google-developed, TypeScript-based web application framework, has arrived, featuring typed forms and a developer preview of standalone components. Standalone components simplify the development of Angular applications by reducing the need for NgModules.…
Node Runs TypeScript Now. Here's Exactly What It Strips, What It Refuses, and What It Costs
Node 24 and 26 run .ts files with no build step and no flags, by replacing types with whitespace. I ran eleven test cases, the TypeScript 7 compiler and tsx against both versions: enums, parameter properties and type imports without the type keyword all break, type errors run anyway, and...