Fix XSS in API Responses in AdonisJS
Cross-Site Scripting (XSS) in APIs occurs when unsanitized user input is reflected in the response body, allowing an attacker to execute scripts in the victim's browser context. In AdonisJS, this usually happens when developers use `response.send()` with raw strings or fail to enforce strict JSON content-types, leading to MIME-sniffing vulnerabilities.
The Vulnerable Pattern
// app/Controllers/Http/ProfileController.ts
public async show({ request, response }) {
const username = request.input('name');
// VULNERABLE: Direct reflection of input without sanitization or JSON enforcement
return response.status(200).send(`User: ${username}`);
}
The Secure Implementation
To kill XSS in AdonisJS APIs: 1. Always use the Validator provider to sanitize inputs using the `escape` rule. 2. Never manually construct HTML strings in your controllers. 3. Use `response.ok()` or `response.json()` to ensure the `Content-Type` is set to `application/json`. This tells the browser to treat the body as data, not executable markup. 4. Implement a strict Content Security Policy (CSP) header via the @adonisjs/shield middleware to block unauthorized script execution.
// app/Controllers/Http/ProfileController.ts import { schema, rules } from '@ioc:Adonis/Core/Validator';public async show({ request, response }) { // 1. Validate and Sanitize input using Adonis Validator const profileSchema = schema.create({ name: schema.string({}, [rules.escape(), rules.trim()]) });
const { name } = await request.validate({ schema: profileSchema });
// 2. SECURE: Return a JSON object. AdonisJS automatically sets ‘Content-Type: application/json’ // and handles proper serialization, preventing the browser from rendering it as HTML. return response.ok({ status: ‘success’, user: name }); }
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.