GuardAPI Logo
GuardAPI

Fix XSS in API Responses in SvelteKit

SvelteKit's `+server.js` endpoints are high-value targets for Reflected XSS. When developers manually construct `Response` objects using untrusted `url.searchParams` or request bodies without strict content-type enforcement or sanitization, they create an execution sink. Modern browsers might mitigate some cases, but improper headers can still lead to script execution in the origin.

The Vulnerable Pattern

// src/routes/api/echo/+server.js
export async function GET({ url }) {
  const message = url.searchParams.get('message');
  // VULNERABLE: Reflecting input directly into an HTML response context
  return new Response(`
User Message: ${message}
`, { headers: { 'Content-Type': 'text/html' } }); }

The Secure Implementation

The vulnerability stems from treating untrusted input as trusted HTML. In the insecure example, an attacker can pass `?message=` to execute arbitrary JS. The fix involves two layers: 1. Contextual Encoding/Sanitization: Using `isomorphic-dompurify` ensures that any HTML tags injected are stripped or neutralized. 2. Content-Type Strictness: Using SvelteKit's `json()` helper forces the browser to treat the response as data, not a document. Additionally, setting `X-Content-Type-Options: nosniff` prevents the browser from 'sniffing' the response body and potentially executing it as a different MIME type.

// src/routes/api/echo/+server.js
import { json } from '@sveltejs/kit';
import DOMPurify from 'isomorphic-dompurify';

export async function GET({ url }) { const message = url.searchParams.get(‘message’) || ”;

// OPTION 1: Use json() helper (Recommended) // This sets Content-Type to application/json, preventing HTML parsing // return json({ message });

// OPTION 2: Sanitize if HTML output is strictly required const cleanMessage = DOMPurify.sanitize(message);

return new Response(<div>User Message: ${cleanMessage}</div>, { headers: { ‘Content-Type’: ‘text/html’, ‘X-Content-Type-Options’: ‘nosniff’ } }); }

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