Handling HTTP Redirects Safely in Node.js Fetch Without SSRF or Loops
Prevent open-redirect SSRF bypasses, infinite redirect chains, and hanging sockets in Node.js web extraction services.
Why this breaks in production
Node.js `fetch()` follows up to 20 redirects automatically by default (`redirect: 'follow'`). While convenient for static API clients, automatic redirect following is a classic security hole in URL previewers and AI web readers.
An attacker can submit `https://evil.example/bounce` (which passes initial DNS validation) and respond with `302 Found -> Location: http://169.254.169.254/latest/meta-data/`. Manual hop-by-hop validation closes that attack vector completely.
Recommended Engineering Approach
Pass `redirect: 'manual'` on every outbound `fetch`
Inspect 3xx statuses explicitly instead of letting Undici follow opaque redirects.
Resolve relative `Location` headers and re-run full SSRF validation
Use `new URL(location, currentUrl)` and verify scheme, private IPs, and DNS records on every single hop.
Enforce a strict hop cap (`MAX_REDIRECTS = 4`) and per-request AbortController timeout
Prevent redirect loops and tarpit servers from tying up Node.js worker threads.
Working Code Example
// CleanSnap automatically handles safe redirect validation and reports finalUrl
const res = await fetch("https://usecleansnap.com/api/v1/extract", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ url: "https://github.com/vercel/next.js" }),
});
const data = await res.json();
console.log({
requested: data.sourceUrl,
resolvedFinalUrl: data.finalUrl,
extractMs: res.headers.get("x-extract-time-ms"),
});Test this workflow in the CleanSnap Playground
Pre-load the Sample Docs Page or paste your own URL to inspect clean Markdown, token savings, and auto-generated cURL / Node / Python / MCP code.
Common Edge Cases & Pitfalls
- Relative redirect locations like `Location: /en/docs` throw if passed directly to `new URL(location)` without the second `currentUrl` base argument.
- Always clear `setTimeout` timers in a `finally` block so Node.js does not leak timer handles under high concurrency.
- Do not forward sensitive `Authorization` headers across cross-origin redirects.
Frequently Asked Questions
How many redirect hops does CleanSnap follow?
CleanSnap safely follows up to 4 verified public HTTP/HTTPS redirect hops, re-checking SSRF rules on every hop.
What timeout does CleanSnap enforce on slow upstream sites?
Every upstream request enforces a strict 10-second `AbortController` timeout and returns HTTP `504 UPSTREAM_TIMEOUT` if exceeded.
Does CleanSnap return the final URL after redirects?
Yes — `finalUrl` in the JSON response always reflects the final destination URL.