GuardAPI Logo
GuardAPI

Fix XSS in API Responses in Feathers

Cross-Site Scripting (XSS) in FeathersJS APIs typically occurs when unsanitized user input is stored in a database and subsequently served in a JSON response. While many modern frontends auto-escape, an attacker can bypass this if the API response is viewed directly in a browser or if the 'Content-Type' is manipulated. To secure a Feathers app, you must intercept the data flow using 'before' or 'after' hooks to sanitize payloads.

The Vulnerable Pattern

const { Service } = require('feathers-memory');

// VULNERABLE: Data is accepted and returned exactly as sent module.exports = function (app) { app.use(‘/messages’, new Service());

app.service(‘messages’).hooks({ before: { create: [] // No sanitization here } }); };

The Secure Implementation

The fix utilizes FeathersJS hooks to implement a 'Sanitize on Input' strategy. By integrating DOMPurify (backed by JSDOM), we strip dangerous HTML and JavaScript from the payload before it reaches the service layer. Additionally, ensure 'helmet' middleware is used in your app.js to set 'X-Content-Type-Options: nosniff' and a strict 'Content-Security-Policy', which prevents browsers from sniffing JSON as HTML and executing embedded scripts.

const createDOMPurify = require('dompurify');
const { JSDOM } = require('jsdom');
const window = new JSDOM('').window;
const purify = createDOMPurify(window);

const sanitizeInput = async (context) => { const { data } = context; if (typeof data.text === ‘string’) { // Strip malicious tags/scripts before persistence data.text = purify.sanitize(data.text); } return context; };

module.exports = function (app) { app.service(‘messages’).hooks({ before: { create: [sanitizeInput], update: [sanitizeInput], patch: [sanitizeInput] } }); };

System Alert • ID: 9046
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.