GuardAPI Logo
GuardAPI

Fix XSS in API Responses in Next.js

API routes in Next.js are a common vector for Reflected XSS when developers bypass the built-in JSON serialization or fail to sanitize inputs that are later rendered in the DOM. Even with 'application/json' headers, content-sniffing or improper handling of user-controlled data in the frontend can lead to script execution. This guide demonstrates how to harden your API endpoints against injection.

The Vulnerable Pattern

// pages/api/profile.js
export default function handler(req, res) {
  const { bio } = req.query;
  // VULNERABLE: Manual string construction and lack of content-type enforcement
  // An attacker can pass bio=
  res.setHeader('Content-Type', 'text/html');
  res.status(200).send(`{"status": "success", "bio": "${bio}"}`);
}

The Secure Implementation

The fix involves three layers of defense. First, we use 'isomorphic-dompurify' to neutralize any HTML/JS payloads within the input. Second, we replace '.send()' with '.json()', which ensures the 'Content-Type' is strictly 'application/json', preventing the browser from interpreting the response as HTML. Finally, we implement 'X-Content-Type-Options: nosniff' to stop browsers from attempting to guess the data type, and a restrictive CSP header to prevent the API route from being framed or executing scripts even if a bypass is found.

// pages/api/profile.js
import DOMPurify from 'isomorphic-dompurify';

export default function handler(req, res) { const { bio } = req.query;

// 1. Sanitize input to strip malicious tags const cleanBio = DOMPurify.sanitize(bio);

// 2. Force ‘application/json’ using the built-in .json() helper // 3. Set ‘X-Content-Type-Options’ to prevent MIME-sniffing res.setHeader(‘X-Content-Type-Options’, ‘nosniff’); res.setHeader(‘Content-Security-Policy’, “default-src ‘none’; frame-ancestors ‘none’;”);

res.status(200).json({ status: ‘success’, bio: cleanBio }); }

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