SSRF guard (fetchGuard)
fetchGuard() blocks private, loopback, link-local, and cloud metadata targets before an outbound request is sent. It checks redirects again so a public URL cannot bounce the request into an internal network.
Any handler that calls fetch() on a URL the user can influence (an avatar fetch, a webhook delivery, an “import from URL” feature, an OAuth discovery endpoint, an embed unfurler) is a Server-Side Request Forgery (SSRF) sink. The canonical exploit is the Aikido write-up in which a contact form that emailed an avatar was redirected to http://169.254.169.254/, the AWS cloud metadata service, which handed back short-lived IAM credentials and pivoted into the startup’s S3 buckets.
Key Recommendation for SSRF guard (fetchGuard)
Use fetchGuard to wrap outbound fetch calls that request user-controlled, dynamic URLs (such as avatar URLs, webhook endpoints, or url imports). Never wrap requests going to hardcoded, static internal services or known, trusted third-party APIs.
When & Where to Use
- ✓Fetching resources (avatars, images, attachments) directly from user-supplied URLs.
- ✓Calling user-configured webhooks or callbacks from your application backend.
- ✓Parsing arbitrary links or URLs for rich embed previews ('unfurling').
When & Where NOT to Use
- ✗Making static outbound API requests to known, trusted external services (e.g. Stripe, SendGrid) where URLs are entirely controlled by your code.
- ✗Communicating with internal microservices, databases, or mesh endpoints (where private IP spaces like 10.0.0.x are expected and must be accessible).
- ✗High-performance proxying where you explicitly intend to relay traffic to arbitrary destinations and DNS resolution is cached separately.
- urlCheck protocolhttp: / https: only
- dnsResolve hostnameto one or more IPs
- ipMatch deny rangesRFC1918, loopback, 169.254.x
- safeDispatch requestredirects re-validated per hop
fetchGuard() returns a guarded wrapper around fetch that refuses to dispatch a request whose target resolves to a dangerous internal address, including every documented cloud metadata IP (AWS / Azure / DigitalOcean 169.254.169.254, Oracle Cloud 192.0.0.192, Alibaba 100.100.100.200).
It is opt-in: only calls made through the returned function (or through helpers that use it by default, such as createWebhookSender() and createA2aClient()) are guarded. DaloyJS does not patch the global fetch, so a plain fetch(url) elsewhere in your code is not checked. Neither are third-party SDKs, node:http, undici, or WebSocket clients that open their own connections. Route every request whose URL a user can influence through safeFetch, and back it with network egress rules (see residual risk).
Quick start
Do not echo the block reason.address-not-allowedmeans "this name exists and points inside your network", whiledns-resolution-failedmeans it does not exist, anderr.messageincludes the resolved IP. Sent back to the caller, either one lets an attacker enumerate internal hostnames one request at a time. Log them; return one generic error.
What gets blocked by default
- Loopback:
127.0.0.0/8,::1. Opt in withallowLoopback: truefor local-dev fixtures. - RFC1918 private:
10.0.0.0/8,172.16.0.0/12,192.168.0.0/16. Opt in withallowPrivate: true. - Link-local (covers every cloud-metadata IP):
169.254.0.0/16,fe80::/10. Opt in withallowLinkLocal: true; the metadata addresses in the floor below stay denied even then. - IPv6 unique-local:
fc00::/7. Opt in withallowUniqueLocal: true. - Always-deny floor (no flag and no
allowAddressesrange lifts these):0.0.0.0/8,100.64.0.0/10(CGNAT, Alibaba metadata),169.254.169.254/32(AWS / Azure / DigitalOcean / GCP metadata),169.254.170.2/32and169.254.170.23/32(AWS ECS task metadata / EKS Pod Identity),192.0.0.0/24(Oracle Cloud metadata), all IANA-reservedTEST-NET/ benchmarking / docs ranges,224.0.0.0/4multicast,240.0.0.0/4reserved, broadcast255.255.255.255, IPv6::/128,ff00::/8andfd00:ec2::254/128(AWS IMDS over IPv6). Your owndenyAddressesentries join this floor. - Protocols other than
http:/https:(file:,data:,gopher:,ftp:,dict:,ldap:). - The Fetch Standard's "bad ports" (SMTP
25, X116000, IRC6667, and the rest of the list), refused withport-not-allowedon every path, including the DNS-pinned one (since 1.14.0). Narrow further withallowPorts.
Limits on every call
Since 1.14.0 every guarded call is bounded, so an attacker-chosen URL that answers slowly or never stops sending cannot tie up your handler or its memory:
timeoutMs(default30000): one deadline for the whole call, covering DNS checks, every redirect hop, the response head, and reading the body. On expiry the call, or the body you are still reading, rejects with aTimeoutError. It combines with anysignalyou pass.0turns it off; only do that when you apply your own deadline.maxResponseBytes(default 10 MiB): a largerContent-Lengthis refused before the body is read, and a body that grows past the limit while streaming errors withSsrfBlockedError("response-too-large").Infinityturns it off.allowPorts(optional): only these destination ports are allowed, for example[443]for an HTTPS-only image fetcher.
createWebhookSender() and createA2aClient() keep their own timeoutMs (and the A2A client its own maxResponseBytes), so they turn the guard's deadline off rather than letting it cap theirs.
IPv6 forms that embed IPv4
A NAT64, 6to4, or Teredo translator turns an IPv6 destination into a connection to the IPv4 address embedded in it, so each of these forms is re-checked against the full IPv4 policy (since 1.3.7 for all but the mapped form). A denied embedded IPv4 denies the IPv6 address:
- IPv4-mapped
::ffff:0:0/96and SIIT::ffff:0:0:0/96 - IPv4-compatible
::/96(other than::and::1, which are classified directly) - NAT64 well-known prefix
64:ff9b::/96 - 6to4
2002::/16 - Teredo
2001::/32(both the server IPv4 and the de-obfuscated client IPv4)
So http://[::ffff:169.254.169.254]/ and http://[64:ff9b::a9fe:a9fe]/ are rejected the same way as http://169.254.169.254/. The local-use NAT64 prefix 64:ff9b:1::/48 is denied outright, because its embedding layout is operator-defined; only an explicit allowAddresses range lifts it. IPv6 literal URLs such as http://[::1]/ are classified by the deny list directly (since 1.3.7) rather than handed to the resolver.
A NAT64 network-specific prefix that your network operator chose cannot be detected from the address alone. If your egress path uses one, add it to denyAddresses:
Redirects are re-validated at every hop
A common SSRF bypass is to return 302 Location: http://169.254.169.254/ from a public host. fetchGuard() follows redirects manually: it re-checks the protocol and re-resolves DNS for every Location header before issuing the next request. Set maxRedirects: 0 to return the 3xx directly, or pass redirect: "manual" per call for the same effect.
An in-memory request body (string, ArrayBuffer or view, Blob, URLSearchParams, FormData) up to maxReplayBodyBytes (default 1 MiB; 0 never buffers) is copied once so a 307 or 308 can replay it on the re-validated next hop (since 1.3.7). Multipart filenames count toward the cap, and the serialized byte length is checked before a body is kept for replay. A 301/302/303 that downgrades to GET drops the body as usual. A body you pass as a ReadableStream or async iterable, the body of a Request you forward (for example ctx.request in a proxy), and an in-memory body over the cap are streamed through without buffering, so a 307/308 of one throws SsrfBlockedError with reason redirect-body-not-replayable instead of a raw TypeError. Buffer the body yourself, or use redirect: "error", when a streamed upload must follow redirects.
Credential headers on cross-origin redirects
When a redirect leaves the original origin, fetchGuard() drops Authorization, Cookie, Proxy-Authorization, and Host. It does not know about your custom credential headers, so an x-api-key would otherwise follow the redirect to the new host. List them in sensitiveHeaders (since 1.14.0), or pass redirect: "error" when a credentialed call should never be redirected:
No TLS downgrade on redirect
A redirect from an https: URL to an http: one is refused with protocol-downgrade (since 1.16.0). A 307/308 would replay the request body — and every header not in the strip list above — in plaintext, and even a 301/302/303 sends the path and query unencrypted. An http: → https: upgrade is always followed. Pass allowProtocolDowngrade: true only for an upstream you know downgrades and that carries nothing confidential; the address and port checks still run on the plaintext hop.
Custom allowlists
allowHosts is a bypass, not an allowlist of safe destinations. An entry skips the DNS and address checks, so list only names whose DNS you control, never one a user, tenant, or third party can point somewhere else. Prefer the host:port form (since 1.14.0). The port rules above still apply to it.
Custom DNS resolution (non-Node runtimes)
The default resolver uses Node’s node:dns/promises.lookup(). On Cloudflare Workers, Deno without --allow-net, or any runtime without Node-style DNS, supply a resolver. It must return every address the runtime might connect to, so query both IPv4 (A) and IPv6 (AAAA) records. A resolver that only asks for A lets a host with a public IPv4 address and an internal IPv6 address (::1, fd00:ec2::254) pass validation.
Pinning is off outside Node, so on these runtimes the rebinding window stays open. Rely on the platform's egress rules as well.
DNS pinning (pinDns)
On Node-like runtimes, fetchGuard() defaults pinDns: true when you do not supply a custom fetch. The socket is then opened through node:http (or node:https) against the exact IP that passed validation, while the original Host header is preserved. That closes the classic DNS-rebinding (TOCTOU) window, where a TTL=0 record answers with a public IP at validation time and 169.254.169.254 at connect time.
Since 1.14.0 https: is pinned as well. The TLS servername (SNI) is the original hostname and the certificate is verified against it, so pinning never weakens TLS. The pinned path does not use HTTP proxy environment variables.
Pass pinDns: false on Workers and other edge runtimes only if you had forced it on. The default is already off when process.versions.node is absent.
The request's AbortSignal is honoured on the pinned path too (since 1.3.7): an abort before dispatch, while waiting for the response head, or while the body streams tears down the socket and rejects with the signal's reason, the same contract as fetch. Timeouts such as AbortSignal.timeout() keep working with DNS pinning on.
Residual risk: DNS rebinding (TOCTOU)
With the default pinDns on Node, rebinding is closed for http: and https:. The window stays open in three cases: a non-Node runtime (no pin path), pinDns: false, and a custom fetch option, which does its own DNS lookup when it connects.
Do not "pin" inside a customfetchby resolving the hostname again. A snippet that callsdns.lookup()in your customfetchand connects to the result (for example through anundicidispatcher) pins the socket to a second lookup thatfetchGuard()never validated. A rebinding attacker answers the first lookup with a public IP and the second with127.0.0.1; in our test the request reached the loopback service. Earlier versions of this page showed that pattern. Use the default pinned path instead, or add egress rules.
Close the remaining cases at the network layer. Run behind a policy that blocks egress to RFC1918, loopback, link-local, and metadata addresses: a Kubernetes NetworkPolicy, a VPC security group or firewall, step-security/harden-runner in CI, or iptables -A OUTPUT -d 169.254.169.254 -j DROP on the host. That neutralises rebinding even for code paths that bypass fetchGuard() entirely.
fetchGuard() remains defense-in-depth on top of these controls.
Error shape
Blocked requests throw SsrfBlockedError with a structured reason:
protocol-not-allowed: URL wasfile:,data:, etc.address-not-allowed: resolved IP fell in a blocked range.dns-resolution-failed: lookup threw or returned no records.too-many-redirects: chain exceededmaxRedirects(default5).credentials-in-url: the URL carried userinfo (http://user@host/), a classic SSRF obfuscation. The credentials are stripped from the URL recorded on the error.invalid-url: URL or Location header could not be parsed.redirect-body-not-replayable: a307/308redirect needed to resend a streamed request body that was already consumed (since 1.3.7).port-not-allowed: the destination port is a Fetch Standard "bad port" or is not inallowPorts(since 1.14.0).response-too-large: the response'sContent-Lengthor streamed body exceededmaxResponseBytes(since 1.14.0). When the body is already streaming, the error surfaces from reading it (res.text(),res.json(), the reader).protocol-downgrade: a redirect went fromhttps:tohttp:andallowProtocolDowngradeis not set (since 1.16.0).
Network failures from the underlying fetch (DNS timeouts, TLS errors, connection refused) bubble through unchanged so your retry logic can distinguish “Daloy refused” from “the upstream is sad.” A timeoutMs expiry rejects with a TimeoutError DOMException.