Fix XSS in API Responses in Polka
Cross-Site Scripting (XSS) in API responses occurs when an endpoint reflects untrusted user input back to the client without proper sanitization or strict Content-Type enforcement. In minimalist Node.js frameworks like Polka, the burden of security falls entirely on the developer. If an attacker can force a browser to render an API response as HTML, they can execute arbitrary JavaScript in the context of the user's session.
The Vulnerable Pattern
const polka = require('polka');
polka() .get(‘/api/search’, (req, res) => { const { q } = req.query; // VULNERABLE: Direct reflection of query param without Content-Type // An attacker can pass ?q= and if the browser // sniffs this as HTML, the script executes. res.end(Results for: ${q}); }) .listen(3000);
The Secure Implementation
To kill XSS in Polka APIs, you must control the browser's interpretation of the data. First, explicitly set 'Content-Type: application/json' to ensure the browser doesn't default to 'text/html'. Second, use the 'X-Content-Type-Options: nosniff' header to prevent legacy browsers from ignoring the Content-Type and performing MIME-sniffing. Finally, always use JSON.stringify() for output to ensure characters like '<' and '>' are properly handled within the JSON context, and implement a restrictive CSP to block any accidental script execution.
const polka = require('polka');polka() .get(‘/api/search’, (req, res) => { const { q } = req.query; const payload = JSON.stringify({ query: q });
// SECURE: Explicitly set Content-Type to application/json res.setHeader('Content-Type', 'application/json'); // SECURE: Prevent MIME-sniffing res.setHeader('X-Content-Type-Options', 'nosniff'); // SECURE: Strict Content Security Policy res.setHeader('Content-Security-Policy', "default-src 'none'; frame-ancestors 'none';"); res.end(payload);
}) .listen(3000);
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.