Fix SSRF (Server Side Request Forgery) in NestJS
SSRF in NestJS occurs when the @nestjs/axios HttpService or raw internal clients execute requests to attacker-controlled URLs. This allows adversaries to pivot into internal networks, hit cloud metadata endpoints (169.254.169.254), or bypass firewalls by using the server as a proxy. If you're passing query params directly into your HTTP client without strict validation, your infrastructure is exposed.
The Vulnerable Pattern
@Get('fetch')
async fetchRemote(@Query('url') url: string) {
// VULNERABLE: Direct injection of user input into the GET request.
// Attacker can pass ?url=http://localhost:6379 or ?url=http://169.254.169.254/latest/meta-data/
const response = await this.httpService.axiosRef.get(url);
return response.data;
}
The Secure Implementation
To kill SSRF, you must adopt a 'Deny All' strategy. First, use the native URL constructor to parse the input; never use regex for URL validation as it is prone to bypasses. Second, implement a strict whitelist of allowed hostnames. Third, disable redirects in your Axios configuration to prevent attackers from bypassing domain checks via an open redirect on a trusted host. For high-security environments, perform a DNS lookup on the hostname and validate that the resulting IP address is not a private, loopback, or link-local address before initiating the connection.
@Get('fetch') async fetchRemote(@Query('url') url: string) { const ALLOWED_DOMAINS = ['api.trusted.com', 'cdn.assets.io']; let parsedUrl: URL;try { parsedUrl = new URL(url); } catch (e) { throw new BadRequestException(‘Invalid URL format’); }
// 1. Enforce HTTPS only if (parsedUrl.protocol !== ‘https:’) { throw new ForbiddenException(‘Only HTTPS is allowed’); }
// 2. Strict Domain Whitelisting if (!ALLOWED_DOMAINS.includes(parsedUrl.hostname)) { throw new ForbiddenException(‘Domain not authorized’); }
// 3. Prevent DNS Rebinding / Internal IP access // In production, resolve hostname and verify it is not in a private range (e.g., 10.x, 192.168.x, 127.x)
const response = await this.httpService.axiosRef.get(parsedUrl.toString(), { timeout: 3000, maxRedirects: 0 // Prevent redirect-based SSRF }); return response.data; }
Your NestJS API
might be exposed to SSRF (Server Side Request Forgery)
74% of NestJS 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.