GuardAPI Logo
GuardAPI

Fix XSS in API Responses in Remix

Remix provides a robust framework for SSR, but XSS vulnerabilities creep in when developers bypass the standard data flow. The primary attack vectors occur when loaders return unsanitized strings as HTML or when the client-side renders API-supplied content using 'dangerouslySetInnerHTML' without a sanitization layer like DOMPurify. To secure a Remix API response, you must enforce strict Content-Type headers and rely on React's automatic escaping.

The Vulnerable Pattern

import { Response } from '@remix-run/node';

// LOADER: Manually constructing a response with incorrect Content-Type export const loader = async () => { const userBio = “<img src=x onerror=alert(‘XSS_SUCCESS’)>”; return new Response(<div>${userBio}</div>, { headers: { ‘Content-Type’: ‘text/html’ } }); };

// COMPONENT: Rendering raw HTML from the API export default function Profile() { const data = useLoaderData(); return <div dangerouslySetInnerHTML={{ __html: data }} />; }

The Secure Implementation

The fix involves three layers: 1. Use the 'json' helper from '@remix-run/node' which forces the 'application/json' Content-Type, preventing the browser from sniffing and executing the payload as HTML. 2. Implement Schema Validation (e.g., Zod) in the loader to ensure incoming data matches expected types. 3. Avoid 'dangerouslySetInnerHTML'. By rendering data within standard JSX tags (e.g.,

{bio}
), React treats the content as a literal string and automatically escapes dangerous characters like <, >, and &, neutralizing any injected scripts.

import { json } from '@remix-run/node';
import { useLoaderData } from '@remix-run/react';
import { z } from 'zod';

const UserSchema = z.object({ bio: z.string() });

export const loader = async () => { const rawData = { bio: "" }; // Validate and return as application/json const validated = UserSchema.parse(rawData); return json(validated); };

export default function Profile() { const { bio } = useLoaderData(); // React automatically escapes string interpolation return

{bio}
; }

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