GuardAPI Logo
GuardAPI

Fix XSS in API Responses in Fastify

API-based XSS in Fastify occurs when untrusted input is reflected in a response without proper sanitization or when the 'Content-Type' is misconfigured, allowing browsers to execute malicious scripts. Even in JSON APIs, 'content-type sniffing' or improper client-side handling of error messages can lead to exploitation. As a researcher, you must ensure strict output encoding and rigid security headers.

The Vulnerable Pattern

fastify.get('/user', async (request, reply) => {
  const { name } = request.query;
  // VULNERABILITY: Manually setting text/html and reflecting raw input
  reply.type('text/html').send(`

Welcome, ${name}

`); });

The Secure Implementation

To kill XSS in Fastify, follow these protocols: 1. Strict Content-Types: Never manually set 'text/html' for API responses. Stick to 'application/json' which browsers do not execute as script. 2. Use @fastify/helmet: This middleware sets 'X-Content-Type-Options: nosniff', preventing the browser from guessing the MIME type and executing a payload hidden in a non-HTML response. 3. Input Validation: Use Fastify's built-in JSON Schema (AJV) to sanitize and restrict input before it hits your logic. 4. Output Encoding: If you must return HTML, use a library like 'dompurify' or 'he' to encode entities. Never trust string interpolation with raw user data.

const fastify = require('fastify')();
const helmet = require('@fastify/helmet');

// 1. Register security headers (CSP, No-Sniff, etc.) fastify.register(helmet);

fastify.get(‘/user’, { schema: { query: { type: ‘object’, properties: { name: { type: ‘string’ } } } } }, async (request, reply) => { const { name } = request.query; // 2. Return JSON objects; Fastify automatically sets application/json // 3. JSON serialization handles basic character escaping return { welcome_message: Welcome, ${name} }; });

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