GuardAPI Logo
GuardAPI

Fix XSS in API Responses in Hapi

API-based XSS occurs when an endpoint reflects untrusted input back to the browser with an insecure Content-Type. In Hapi.js, while the framework defaults to JSON, manual overrides to 'text/html' or poorly configured error handlers can lead to script injection. If an attacker can trick a browser into rendering a response as HTML, your API becomes a delivery vector for malicious payloads.

The Vulnerable Pattern

server.route({
  method: 'GET',
  path: '/api/user/{id}',
  handler: (request, h) => {
    const { id } = request.params;
    const { redirect } = request.query;
    // VULNERABILITY: Reflecting 'redirect' query param in an HTML response
    return h.response(`User ${id} not found. Go back to Dashboard`)
            .type('text/html');
  }
});

The Secure Implementation

To kill XSS in Hapi APIs, follow three rules: 1. Never manually set the Content-Type to 'text/html' for API responses. Let Hapi default to 'application/json' by returning plain objects. 2. Use Joi for strict input validation to ensure parameters like IDs or URLs conform to expected patterns, neutralizing unexpected payloads before they reach your logic. 3. If you must return HTML, use a templating engine with automatic contextual escaping (like Vision with Handlebars) rather than raw string concatenation. Forcing 'application/json' is your primary defense; it tells the browser to treat the body as data, not markup.

const Joi = require('joi');

server.route({ method: ‘GET’, path: ‘/api/user/{id}’, options: { validate: { params: { id: Joi.string().alphanum() }, query: { redirect: Joi.string().uri({ scheme: [‘http’, ‘https’] }) } } }, handler: (request, h) => { const { id } = request.params; // SECURE: Return a JSON object. Hapi automatically sets Content-Type to application/json // This prevents the browser from interpreting the response as executable HTML. return { error: ‘Not Found’, message: User ${id} was not found, suggested_path: request.query.redirect }; } });

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