Fix XSS in API Responses in Gatsby
Gatsby's static-site generation doesn't make you bulletproof. If you're hydrating your frontend with dynamic API data and piping it into the DOM without sanitization, you're handing an XSS vector to anyone who can poison your backend. The most common fail point is leveraging React's 'dangerouslySetInnerHTML' on raw, unvalidated API strings. Stop trusting your upstream; sanitize your sinks.
The Vulnerable Pattern
import React from 'react';const ProductDescription = ({ apiData }) => { // VULNERABLE: Direct injection of API response into the DOM return (
{apiData.name}
); };
export default ProductDescription;
The Secure Implementation
The vulnerability exists because 'dangerouslySetInnerHTML' explicitly instructs React to bypass its default XSS protections (which involve automatic character escaping). If the API response contains a payload like , it executes immediately in the browser. The fix implements 'isomorphic-dompurify' to parse the HTML and strip dangerous elements and attributes (scripts, event handlers, etc.) before they hit the DOM. For SSR/Gatsby builds, 'isomorphic-dompurify' is preferred as it handles both Node.js and browser environments seamlessly.
import React from 'react'; import DOMPurify from 'isomorphic-dompurify';const ProductDescription = ({ apiData }) => { // SECURE: Use isomorphic-dompurify to strip malicious payloads before rendering const cleanDescription = DOMPurify.sanitize(apiData.description);
return (
{apiData.name}
{/* If you must render HTML, use a sanitized string */}{/* For plain text, always use standard JSX braces for auto-escaping */}); };{apiData.meta_info}
export default ProductDescription;
Your API Responses API
might be exposed to XSS
74% of API Responses 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.