# SSRF-Safe Fetching in Node.js: Validate DNS at Connect Time

> If your app or AI agent fetches user-supplied URLs, string checks are not enough. Build a fetch wrapper that validates every resolved IP at connect time, re-checks redirects and caps responses.

- Published: 2026-09-29
- Updated: 2026-10-07
- Category: Tutorials
- Type: tutorial
- Tags: nodejs, security, ssrf, undici
- Sources: 4
- Canonical: https://rajatxautomatedcontent.vercel.app/articles/ssrf-safe-fetch-nodejs

---

## What you will build

A `safeFetch()` wrapper for Node.js that you can hand arbitrary URLs — from users, RSS feeds or an AI agent — without letting those URLs reach your internal network or a cloud metadata endpoint.

## Why string checks are not enough

Server-side request forgery (SSRF) occurs when an application fetches a remote resource without validating the user-supplied URL, letting an attacker make the server send requests to unexpected destinations — even ones protected by a firewall [S1]. Checking the hostname as a string fails in several ways:

- **Alternate IP encodings.** In Node.js, `new URL("http://2130706433/").hostname` and `new URL("http://0x7f.1/").hostname` both return `127.0.0.1`, because the WHATWG URL parser normalizes numeric hosts.
- **DNS answers can change** between the moment you check a hostname and the moment you connect; the OWASP cheat sheet discusses this under DNS pinning [S2].
- **Redirects.** A harmless URL can redirect to a dangerous one [S2].
- **Cloud metadata.** Addresses such as `169.254.169.254` expose instance credentials on many cloud platforms and are a classic target [S2].

The robust approach: validate the IP you actually connect to, every time you connect.

## Prerequisites

Node.js (the built-in `net` and `dns` modules) and the `undici` package:

```bash
npm install undici
```

## Step-by-step

### 1. Classify addresses with net.BlockList

`net.BlockList` lets you declare address ranges with `addSubnet()` and test an address with `check()` [S3].

```ts
import { BlockList, isIP } from "node:net";

const blocked = new BlockList();
const v4: Array<[string, number]> = [
  ["0.0.0.0", 8],
  ["10.0.0.0", 8],
  ["100.64.0.0", 10],
  ["127.0.0.0", 8],
  ["169.254.0.0", 16],
  ["172.16.0.0", 12],
  ["192.168.0.0", 16],
];
const v6: Array<[string, number]> = [
  ["::1", 128],
  ["fc00::", 7],
  ["fe80::", 10],
];
for (const [network, prefix] of v4) blocked.addSubnet(network, prefix, "ipv4");
for (const [network, prefix] of v6) blocked.addSubnet(network, prefix, "ipv6");

export function isPrivate(address: string): boolean {
  const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(address);
  const ip = mapped ? mapped[1] : address;
  const family = isIP(ip);
  if (family === 4) return blocked.check(ip, "ipv4");
  if (family === 6) return blocked.check(ip, "ipv6");
  return true; // not an IP address at all: treat as unsafe
}
```

### 2. Validate DNS answers at connect time

Resolve and validate inside the connection's `lookup` hook, so the address you check is the address you connect to. undici's `Agent` accepts connection options for its socket connector, including a custom `lookup` [S4].

```ts
import { lookup } from "node:dns";
import { Agent } from "undici";
import { isPrivate } from "./ip";

export const safeAgent = new Agent({
  connect: {
    lookup(hostname, options, callback) {
      lookup(hostname, { ...options, all: true }, (error, addresses) => {
        if (error) return callback(error, "", 0);
        if (addresses.length === 0 || addresses.some((a) => isPrivate(a.address))) {
          return callback(new Error(`Blocked non-public address for ${hostname}`), "", 0);
        }
        if (options.all) return callback(null, addresses);
        callback(null, addresses[0].address, addresses[0].family);
      });
    },
  },
});
```

Treating a mixed answer (one public and one private address) as unsafe is deliberate — an attacker controls which record you would get.

### 3. Follow redirects manually and re-validate every hop

IP-literal hosts never go through DNS lookup, so check them before connecting. Then disable automatic redirects and validate each `Location` yourself.

```ts
import { isIP } from "node:net";
import { fetch } from "undici";
import { safeAgent } from "./agent";
import { isPrivate } from "./ip";

export async function safeFetch(input: string, maxRedirects = 5) {
  let url = new URL(input);
  for (let hop = 0; hop <= maxRedirects; hop++) {
    if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error("Blocked protocol");
    if (url.username || url.password) throw new Error("Credentials in URLs are not allowed");
    const host = url.hostname.replace(/^\[|\]$/g, "");
    if (host === "localhost" || (isIP(host) && isPrivate(host))) throw new Error("Blocked host");

    const response = await fetch(url, {
      dispatcher: safeAgent,
      redirect: "manual",
      signal: AbortSignal.timeout(15_000),
    });
    const location = response.headers.get("location");
    if (response.status >= 300 && response.status < 400 && location) {
      url = new URL(location, url);
      continue;
    }
    return response;
  }
  throw new Error("Too many redirects");
}
```

### 4. Cap time and size

Always set a timeout (as above), stop reading the body after a byte budget, and reject content types you do not expect. An unbounded response body is a denial-of-service vector even when the destination is legitimate.

## Troubleshooting

| Symptom                  | Cause                                               | Fix                                                                 |
| ------------------------ | --------------------------------------------------- | ------------------------------------------------------------------- |
| A public site is blocked | Its DNS returns a mix of public and private records | Expected behavior — allow-list that host explicitly if you trust it |
| Requests hang            | No timeouts                                         | Use `AbortSignal.timeout()` and the agent's header/body timeouts    |
| IPv6-only sites fail     | The lookup hook ignores `options.all`               | Return all addresses when `options.all` is set                      |

## Next steps

- Prefer an allow-list of destinations whenever your use case allows it; the OWASP cheat sheet recommends allow-listing where the set of targets is known [S2].
- Network controls are half the story for AI agents: the pages they fetch can also carry instructions aimed at your model. See [Prompt Injection in RAG Pipelines](/articles/prompt-injection-rag-untrusted-input).

## FAQ

**Is an allow-list better than a block-list for SSRF?**

When the set of destinations is known, yes. Block-lists are the fallback for apps that must fetch arbitrary public URLs, such as feed readers and AI research agents.

**Why validate IP addresses at connect time?**

Because DNS answers can change between the moment you check a hostname and the moment you connect. Validating inside the connection lookup checks the address you actually use.

**Does this stop every SSRF attack?**

It removes the most common paths, but you should also restrict outbound traffic at the network level and keep response sizes and timeouts bounded.

## Sources

- [S1] A10:2021 – Server-Side Request Forgery (SSRF) — OWASP. <https://owasp.org/Top10/2021/A10_2021-Server-Side_Request_Forgery_%28SSRF%29/> (retrieved 2026-09-30, trust: high)
- [S2] Server-Side Request Forgery Prevention Cheat Sheet — OWASP Cheat Sheet Series. <https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html> (retrieved 2026-09-30, trust: high)
- [S3] Net — Node.js documentation — Node.js. <https://nodejs.org/api/net.html> (retrieved 2026-09-30, trust: official)
- [S4] Undici — HTTP/1.1 client for Node.js — Node.js. <https://undici.nodejs.org/> (retrieved 2026-09-30, trust: official)

---

Source: AI Dev Hub — https://rajatxautomatedcontent.vercel.app/articles/ssrf-safe-fetch-nodejs
