GuardAPI Logo
GuardAPI
Automated Security Protocol

How to fix XSS in API Responses
in Vapor (Swift)

Executive Summary

XSS in APIs occurs when unsanitized user input is reflected in a response that the browser interprets as HTML. In Vapor, this risk manifests when developers manually set 'Content-Type: text/html' or return raw strings without proper encoding. To kill this bug, you must enforce strict 'application/json' content types or utilize context-aware HTML encoding.

The Vulnerable Pattern

VULNERABLE CODE
app.get("user-profile") { req -> Response in
    let username = req.query["username"] ?? "Guest"
    // VULNERABILITY: Manually crafting HTML with unsanitized input and setting text/html
    let html = "

Profile of: \(username)

" let res = Response(status: .ok, body: .init(string: html)) res.headers.replaceOrAdd(name: .contentType, value: "text/html") return res }

The Secure Implementation

The vulnerable example allows an attacker to pass '' as the username, which the browser executes because of the 'text/html' header. The fix involves using Vapor's 'Content' protocol, which automatically serializes the data to JSON and sets the 'Content-Type' to 'application/json'. Modern browsers do not execute scripts found within JSON bodies. If HTML output is strictly required, use the Leaf templating engine which performs automatic HTML entity encoding by default.

SECURE CODE
struct UserProfile: Content {
    let username: String
}

app.get(“user-profile”) { req -> UserProfile in let username = req.query[“username”] ?? “Guest” // SECURE: Vapor’s Content protocol defaults to application/json, // ensuring the browser treats the payload as data, not executable code. return UserProfile(username: username) }

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