Fix XSS in API Responses in Astro
Astro server endpoints (API routes) are high-value targets. If your API reflects user-controlled input directly into a response body without strict header enforcement or proper sanitization, you've opened a reflected XSS vector. Browsers may interpret these responses as HTML, executing malicious scripts in the context of your origin.
The Vulnerable Pattern
export async function GET({ request }) {
const url = new URL(request.url);
const query = url.searchParams.get('query');
// DANGER: Reflecting input directly with text/html content type
return new Response(`Results for: ${query}`, {
headers: { 'Content-Type': 'text/html' }
});
}
The Secure Implementation
The fix involves three layers of defense. First, switch the 'Content-Type' to 'application/json'; modern browsers will not execute script blocks within a JSON payload. Second, set the 'X-Content-Type-Options: nosniff' header to prevent the browser from 'sniffing' the response body and deciding to render it as HTML regardless of the header. Third, if you must return HTML, use a robust sanitization library like 'sanitize-html' to strip dangerous tags (script, iframe, etc.) and event handlers (onload, onerror) from the input before it is serialized into the response.
import sanitizeHtml from 'sanitize-html';export async function GET({ request }) { const url = new URL(request.url); const query = url.searchParams.get(‘query’) || ”;
// 1. Sanitize input if HTML output is strictly required const cleanQuery = sanitizeHtml(query);
// 2. Prefer JSON for APIs to prevent browser execution return new Response(JSON.stringify({ results: cleanQuery }), { status: 200, headers: { ‘Content-Type’: ‘application/json’, ‘X-Content-Type-Options’: ‘nosniff’, ‘Content-Security-Policy’: “default-src ‘none’;” } }); }
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.