GuardAPI Logo
GuardAPI

Fix XSS in API Responses in Nitro

Nitro's high-performance event handling can be a double-edged sword. If you're echoing user-controlled input directly into the response without explicitly defining the Content-Type or sanitizing the payload, you're opening the door for Reflected XSS. Attackers can leverage browser MIME-sniffing to treat your API response as HTML, executing arbitrary scripts in the context of your domain.

The Vulnerable Pattern

export default defineEventHandler((event) => {
  const { user } = getQuery(event);

// VULNERABLE: Returning a string with user input without setting headers. // If ‘user’ is , the browser may render it as HTML. return <html><body>User: ${user}</body></html>; });

The Secure Implementation

To kill XSS in Nitro APIs, you must control the browser's interpretation of the payload. First, never return raw strings containing user input; Nitro's default behavior might default to 'text/html'. Second, explicitly set the 'Content-Type' header to 'application/json'. Third, use the 'X-Content-Type-Options: nosniff' header to stop browsers from trying to guess the content type based on the response body. By returning an object instead of a string, Nitro handles the serialization, ensuring the user input is treated as a literal string within a JSON structure, not executable code.

import { createError } from 'h3';

export default defineEventHandler((event) => { const { user } = getQuery(event);

// 1. Force Content-Type to application/json to prevent HTML parsing setResponseHeader(event, ‘Content-Type’, ‘application/json’);

// 2. Prevent MIME-type sniffing setResponseHeader(event, ‘X-Content-Type-Options’, ‘nosniff’);

// 3. Return as an object (Nitro automatically serializes to valid JSON) return { status: ‘success’, data: { username: user } }; });

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