Fix XSS in API Responses in Blitz.js
Blitz.js API routes, while powerful, inherit the standard security pitfalls of Node.js web frameworks. XSS in API responses occurs when untrusted user input is reflected back to the client without proper sanitization or incorrect Content-Type headers, allowing an attacker to execute arbitrary JavaScript in the context of the victim's session.
The Vulnerable Pattern
// app/api/user-info.ts import { NextApiRequest, NextApiResponse } from "blitz"
export default async function handler(req: NextApiRequest, res: NextApiResponse) { const { username } = req.query // VULNERABLE: Directly reflecting query params in a response that defaults to text/html res.status(200).send(<div>User: ${username}</div>) }
The Secure Implementation
The vulnerability stems from the API route reflecting raw user input while the browser potentially interprets the response as HTML. To mitigate this: 1) Always use res.json() instead of res.send() to force an application/json MIME type. 2) Explicitly set the 'X-Content-Type-Options: nosniff' header to prevent browsers from MIME-sniffing the response into executable HTML. 3) Use an escaping library like 'escape-html' for any dynamic data that must be reflected, ensuring special characters like <, >, and & are neutralized.
// app/api/user-info.ts import { NextApiRequest, NextApiResponse } from "blitz" import escapeHtml from "escape-html"export default async function handler(req: NextApiRequest, res: NextApiResponse) { const { username } = req.query const safeUsername = typeof username === “string” ? escapeHtml(username) : ""
// SECURE: Enforce JSON response and set security headers res.setHeader(“Content-Type”, “application/json”) res.setHeader(“X-Content-Type-Options”, “nosniff”)
return res.status(200).json({ user: safeUsername, status: “success” }) }
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.