Fix SSRF (Server Side Request Forgery) in Next.js
SSRF in Next.js is a high-impact vulnerability typically found in API routes or server-side functions like getServerSideProps. It allows an attacker to force the server to execute requests to internal resources, metadata services (IMDS), or restricted internal microservices. If you're blindly passing user-provided URLs to fetch(), you're handing over your VPC's keys.
The Vulnerable Pattern
export default async function handler(req, res) {
const { targetUrl } = req.query;
// CRITICAL: No validation on targetUrl.
// Attacker can pass 'http://169.254.169.254/latest/meta-data/' to steal AWS creds.
const response = await fetch(targetUrl);
const data = await response.json();
res.status(200).json(data);
}
The Secure Implementation
The secure implementation utilizes a defense-in-depth approach. First, it uses the native URL constructor to parse the input, preventing basic obfuscation bypasses. It enforces the HTTPS protocol to stop local file (file://) or gopher (gopher://) attacks. Most importantly, it implements a strict hostname allowlist. For enterprise-grade security, developers should also resolve the hostname to an IP and verify it does not fall within private/reserved IP ranges (RFC 1918) to prevent DNS Rebinding attacks that target internal network interfaces.
import { URL } from 'url';const ALLOWED_HOSTS = [‘api.trusted-partner.com’, ‘cdn.myapp.com’];
export default async function handler(req, res) { const { targetUrl } = req.query;
try { const parsed = new URL(targetUrl);
// 1. Enforce HTTPS only if (parsed.protocol !== 'https:') { return res.status(400).json({ error: 'Insecure protocol' }); } // 2. Strict Hostname Allowlisting if (!ALLOWED_HOSTS.includes(parsed.hostname)) { return res.status(403).json({ error: 'Forbidden target' }); } const response = await fetch(parsed.toString()); const data = await response.json(); res.status(200).json(data);
} catch (err) { res.status(400).json({ error: ‘Invalid URL’ }); } }
Your Next.js API
might be exposed to SSRF (Server Side Request Forgery)
74% of Next.js apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.