GuardAPI Logo
GuardAPI

Fix XSS in API Responses in Sails

Sails.js APIs are frequently pwned when developers treat `res.send()` as a generic sink for unvalidated input. If you're reflecting raw parameters back to the client without strict Content-Type enforcement or proper output encoding, you're providing an execution primitive for Reflected XSS. Modern browsers might sniff 'text/html' from your JSON if you aren't careful, leading to script execution in the victim's session.

The Vulnerable Pattern

// api/controllers/UserController.js
module.exports = {
  search: async function (req, res) {
    const query = req.param('q');
    // VULNERABLE: Reflecting raw input directly into the response body.
    // If 'q' contains , it executes in the browser.
    return res.send("Results for: " + query);
  }
};

The Secure Implementation

The fix targets the root of the injection. First, we replace `res.send()` with `res.json()`. This explicitly sets the `Content-Type` header to `application/json`, which tells the browser not to interpret the body as HTML. Second, we use `validator.escape()` to neutralize HTML entities, ensuring that even if the JSON is somehow rendered as text, the payloads remain inert. Finally, ensure your `config/http.js` includes the `nosniff` middleware to prevent browsers from MIME-sniffing the response into a different, executable context.

// api/controllers/UserController.js
const validator = require('validator');

module.exports = { search: async function (req, res) { const query = req.param(‘q’) || ”;

// 1. Sanitize/Escape the output
const safeQuery = validator.escape(query);

// 2. Force application/json to prevent HTML parsing
// 3. Use structured data instead of raw strings
return res.json({
  status: 'success',
  resultsFor: safeQuery
});

} };

System Alert • ID: 5527
Target: API Responses API
Potential Vulnerability

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.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

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.