GuardAPI Logo
GuardAPI

Fix XSS in API Responses in Koa

Koa's minimalist design means it won't save you from yourself. If you're blindly reflecting user input into `ctx.body` without strict content-type enforcement or output encoding, you're handing an XSS vector to any script kiddie with a browser. In an API context, the primary risk is the browser misinterpreting JSON or raw text as HTML and executing embedded payloads.

The Vulnerable Pattern

const Koa = require('koa');
const app = new Koa();

app.use(async (ctx) => { const { username } = ctx.query; // VULNERABILITY: Direct reflection of unsanitized input. // If ctx.type isn’t set, Koa might default to ‘text/html’ or ‘text/plain’. // Payload: ?username= ctx.body = User profile: ${username}; });

app.listen(3000);

The Secure Implementation

To kill XSS in Koa APIs, follow the defense-in-depth triad: First, enforce `ctx.type = 'application/json'` to ensure browsers don't attempt to sniff the response as HTML. Second, integrate `koa-helmet` to implement a strict Content Security Policy (CSP) and `X-Content-Type-Options: nosniff`. Third, use an escaping library like `escape-html` for any dynamic data reflected in the response body. Never trust the client; sanitize every byte.

const Koa = require('koa');
const helmet = require('koa-helmet');
const escapeHtml = require('escape-html');
const app = new Koa();

// 1. Use Helmet to set secure headers, including CSP and X-Content-Type-Options app.use(helmet());

app.use(async (ctx) => { const { username } = ctx.query;

// 2. Force the Content-Type to application/json to prevent HTML parsing ctx.type = ‘application/json’;

// 3. Escape dynamic content even if you think it’s just JSON // 4. Return an object so Koa stringifies it as JSON automatically ctx.body = { status: ‘success’, message: User profile: ${escapeHtml(username)} }; });

app.listen(3000);

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