GuardAPI Logo
GuardAPI

Fix XSS in API Responses in Axum

Cross-Site Scripting (XSS) in Rust-based APIs occurs when user-controlled data is reflected in a response that the browser interprets as HTML. In Axum, this usually happens by incorrectly using the `Html` response wrapper or failing to set strict `Content-Type` headers, allowing an attacker to execute arbitrary JavaScript in the context of the victim's session.

The Vulnerable Pattern

use axum::{extract::Query, response::Html, routing::get, Router};
use serde::Deserialize;

#[derive(Deserialize)] struct SearchParams { q: String, }

// VULNERABLE: Directly embedding unescaped input into an Html response async fn search(Query(params): Query) -> Html { Html(format!(“

Results for: {}

”, params.q)) }

pub fn app() -> Router { Router::new().route(“/search”, get(search)) }

The Secure Implementation

The vulnerability exists because the `Html` wrapper sets the 'Content-Type' to 'text/html', prompting the browser to parse the response body for script tags. To fix this, always return data using `axum::Json`. This forces the 'application/json' MIME type, which browsers will not execute as HTML. Additionally, the `Json` extractor ensures that special characters are properly handled during serialization. For defense-in-depth, implement a middleware to append 'X-Content-Type-Options: nosniff' and a restrictive 'Content-Security-Policy' header to all API responses.

use axum::{extract::Query, Json, routing::get, Router};
use serde::{Deserialize, Serialize};

#[derive(Deserialize)] struct SearchParams { q: String, }

#[derive(Serialize)] struct SearchResponse { query: String, results: Vec, }

// SECURE: Use axum::Json to force ‘application/json’ and automatic escaping async fn search(Query(params): Query) -> Json { Json(SearchResponse { query: params.q, results: vec![], }) }

pub fn app() -> Router { Router::new().route(“/search”, get(search)) }

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