Short answer: if your server fetches a URL that a user (or an LLM) supplied, an attacker can point it at addresses only your server can reach, like http://169.254.169.254/ cloud metadata, localhost admin ports or internal services. That is server-side request forgery (SSRF). To fix it, allow only http and https, resolve the hostname and reject private, loopback, link-local and metadata IP ranges, handle redirects manually and re-check every hop, set a timeout and a response size limit, and never return the raw response body to the caller. For anything high risk, route these requests through a filtering agent or an egress proxy.
Vibe-coded apps add SSRF without anyone noticing, because the features that cause it are popular: "paste a link to get a preview", "summarize this article with AI", "import from URL", "add a webhook URL" and "fetch this image and resize it". Lovable, Bolt, v0 and Cursor all happily generate a route that does fetch(req.body.url).
What the vulnerable code looks like
// app/api/preview/route.ts (vulnerable)
export async function POST(req: Request) {
const { url } = await req.json();
const res = await fetch(url);
const html = await res.text();
return Response.json({ html });
}
An attacker sends:
http://169.254.169.254/latest/meta-data/iam/security-credentials/on AWS EC2 or ECS style hosts, orhttp://metadata.google.internal/on Google Cloud, to try to read instance credentials.http://localhost:5432,http://127.0.0.1:6379orhttp://localhost:3000/api/adminto reach services that trust local traffic.http://10.0.0.5:8080or other private addresses to scan your internal network.file:///etc/passwdif the HTTP client supports other schemes.
Because the route returns the body, the attacker reads the result directly. Even a "blind" SSRF (no body returned) lets someone probe which internal ports are open by timing responses.
How bad this is depends on where you host. On serverless platforms like Vercel or Cloudflare Workers there is usually no instance metadata service to steal from, but you can still be used to hit internal APIs, other tenants' preview URLs, or third party services with your server's IP and reputation. On a VPS, Docker host, Fly.io, Railway, Render, Replit or anything on AWS, GCP or Azure VMs, the internal network and metadata endpoints are a real target.
The fix: a safe fetch helper
Put all user-driven fetching through one function:
// lib/safe-fetch.ts (Node.js runtime)
import { lookup } from "node:dns/promises";
import ipaddr from "ipaddr.js";
const MAX_BYTES = 2 * 1024 * 1024; // 2 MB
const MAX_REDIRECTS = 3;
async function assertPublicUrl(raw: string): Promise<URL> {
const url = new URL(raw);
if (url.protocol !== "http:" && url.protocol !== "https:") {
throw new Error("Only http and https URLs are allowed");
}
if (url.username || url.password) throw new Error("Credentials in URL not allowed");
const addresses = await lookup(url.hostname, { all: true });
for (const { address } of addresses) {
let ip = ipaddr.parse(address);
if (ip.kind() === "ipv6" && (ip as ipaddr.IPv6).isIPv4MappedAddress()) {
ip = (ip as ipaddr.IPv6).toIPv4Address();
}
if (ip.range() !== "unicast") {
throw new Error("URL resolves to a non-public address");
}
}
return url;
}
export async function safeFetch(raw: string): Promise<string> {
let current = raw;
for (let i = 0; i <= MAX_REDIRECTS; i++) {
const url = await assertPublicUrl(current);
const res = await fetch(url, {
redirect: "manual",
signal: AbortSignal.timeout(5000),
headers: { "user-agent": "MyAppPreviewBot/1.0" },
});
if (res.status >= 300 && res.status < 400) {
const next = res.headers.get("location");
if (!next) throw new Error("Redirect without location");
current = new URL(next, url).toString(); // re-checked on the next loop
continue;
}
const reader = res.body?.getReader();
if (!reader) return "";
const chunks: Uint8Array[] = [];
let total = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
total += value.byteLength;
if (total > MAX_BYTES) {
await reader.cancel();
throw new Error("Response too large");
}
chunks.push(value);
}
return Buffer.concat(chunks).toString("utf8");
}
throw new Error("Too many redirects");
}
What each part does:
- Protocol check blocks
file:,gopher:,ftp:anddata:. - DNS resolution plus range check blocks hostnames that point at private space.
ipaddr.jsclassifies addresses: anything that is notunicast(that is,private,loopback,linkLocal,uniqueLocal,carrierGradeNat,unspecifiedand so on) is rejected. This catcheslocalhost,127.0.0.1,10.x,192.168.x,169.254.169.254and IPv6 equivalents, plus tricks like decimal IPs (http://2130706433/) because the URL parser and DNS normalize them first. - Manual redirects stop the classic bypass where a public URL answers with
302 Location: http://169.254.169.254/. - Timeout and size limit stop someone from tying up your function with a slow or endless response.
The DNS rebinding gap
The helper above checks DNS, then fetch resolves the hostname again. A hostile DNS server can answer with a public IP the first time and 127.0.0.1 the second time (DNS rebinding). For most link preview features the helper is a big improvement, but for high value targets close the gap:
- Use a filtering HTTP agent such as
request-filtering-agentwithnode-fetchoraxios, which checks the IP at connection time. - Or send all outbound user-driven requests through an egress proxy that only allows public destinations.
- Or run the fetcher in an isolated environment with no access to internal networks or metadata (a separate serverless function or worker with no secrets).
On AWS, also require IMDSv2 (session tokens), which blocks most simple SSRF reads of instance metadata.
Do not return the raw response
Return only what the feature needs. A link preview needs a title, description and image URL, not the full HTML:
const html = await safeFetch(url);
const title = html.match(/<title[^>]*>([^<]{0,200})/i)?.[1] ?? "";
return Response.json({ title });
If you render fetched HTML anywhere, sanitize it first, or you have traded SSRF for XSS. See XSS and dangerouslySetInnerHTML in React and Next.js.
Other places SSRF hides in AI-built apps
AI agents with a "browse" or "fetch URL" tool. If an LLM decides which URL to fetch, a prompt injection in any page or document can steer it to internal addresses. Route the tool through safeFetch and treat model output as untrusted input. More in prompt injection in AI apps.
User-configured webhooks. Letting customers set a webhook URL means your server will POST to whatever they enter. Validate it with the same checks when it is saved and again on every delivery, since DNS can change later.
Image proxies and next/image. A config like this lets anyone use your /_next/image endpoint to fetch and process images from any host:
// next.config.js (too broad)
images: { remotePatterns: [{ protocol: "https", hostname: "**" }] }
List the specific hosts you need, such as your Supabase Storage domain.
Server Actions on old Next.js versions. Next.js versions before 14.1.1 had an SSRF issue (CVE-2024-34351) in Server Actions that redirect, exploitable through a manipulated Host header on self-hosted apps. Upgrade, and see Next.js Server Actions security for the rest of the checklist.
Supabase Edge Functions. They run on Deno, where the same rules apply: validate the URL scheme, block private ranges, set redirect: "manual" and a timeout. Keep the service role key out of any function that fetches user URLs if you can. See Supabase Edge Functions security.
Also require auth and rate limits
A URL fetcher is a free proxy for anyone on the internet if the route is public. Require a signed-in user, rate limit per user and per IP, and log the requested hosts. Securing Next.js API routes and rate limiting API routes cover both.
Quick test
Against your own app (never someone else's), submit each of these to every feature that takes a URL and confirm each one is rejected:
http://127.0.0.1/andhttp://localhost:3000/http://169.254.169.254/latest/meta-data/http://[::1]/andhttp://2130706433/file:///etc/passwd- A public URL you control that redirects to
http://127.0.0.1/
If any of these return content, an error that reveals internal details, or a noticeably different response time, the feature needs the fix above.
Get an automated check
PreflightPR reviews AI-built apps for routes that fetch user-supplied URLs, unauthenticated API routes, leaked keys, missing Supabase RLS and other launch blockers. Run a free scan on a public repo for a launch score and a prioritized fix list, or install the PreflightPR GitHub App to check every pull request before it merges.