Fix SSRF (Server Side Request Forgery) in Gatsby
SSRF in Gatsby environments usually manifests within Gatsby Functions (Serverless). When your /api/ routes accept user-provided URLs to fetch external data, you are essentially providing an unauthenticated proxy. Attackers can leverage this to hit internal metadata services (169.254.169.254), scan internal network ports, or bypass firewalls. If you aren't validating the destination, you're owned.
The Vulnerable Pattern
// src/api/fetch-meta.js import axios from 'axios';
export default async function handler(req, res) { const { remoteUrl } = req.query; // VULNERABILITY: Directly fetching user-controlled input // An attacker can pass ?remoteUrl=http://169.254.169.254/latest/meta-data/ const response = await axios.get(remoteUrl); res.status(200).json(response.data); }
The Secure Implementation
The fix involves three layers of defense. First, use the native 'URL' constructor to parse the input; never use regex for URL parsing as it is prone to bypasses. Second, implement a strict allow-list of hostnames to ensure the server only talks to known-good entities. Third, harden the HTTP client by disabling redirects (maxRedirects: 0) to prevent 'Open Redirect' to SSRF escalations, and set short timeouts to prevent resource exhaustion via slow-loris style attacks on internal endpoints.
// src/api/fetch-meta.js import axios from 'axios'; import { URL } from 'url';const ALLOWED_DOMAINS = [‘api.trusted-partner.com’, ‘cdn.myapp.com’];
export default async function handler(req, res) { const { remoteUrl } = req.query;
try { const parsedUrl = new URL(remoteUrl);
// 1. Enforce Protocol if (parsedUrl.protocol !== 'https:') { return res.status(400).json({ error: 'Insecure protocol' }); } // 2. Strict Hostname Allow-listing if (!ALLOWED_DOMAINS.includes(parsedUrl.hostname)) { return res.status(403).json({ error: 'Disallowed destination' }); } // 3. Prevent DNS Rebinding & Internal Redirects const response = await axios.get(parsedUrl.href, { timeout: 3000, maxRedirects: 0, validateStatus: (status) => status === 200 }); res.status(200).json(response.data);
} catch (err) { res.status(500).json({ error: ‘Request failed’ }); } }
Your Gatsby API
might be exposed to SSRF (Server Side Request Forgery)
74% of Gatsby 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.