Cross-Site Scripting (XSS)
What Is This Vulnerability?
Cross-site scripting allows an attacker to inject malicious scripts into web pages viewed by other users. The injected script runs in the context of the victim's browser session, giving the attacker access to cookies, session tokens, and the ability to perform actions on behalf of the user.
Why It Happens
XSS occurs when an application includes untrusted data in its HTML output without proper encoding or escaping. Common sources include URL parameters reflected in the page, user-generated content stored in a database, or DOM manipulation using innerHTML with unsanitized values.
Example Code
export default function SearchResults({ query }: { query: string }) {
return (
<div>
<h1>Results for:</h1>
<div dangerouslySetInnerHTML={{ __html: query }} />
</div>
);
}import DOMPurify from "isomorphic-dompurify";
export default function SearchResults({ query }: { query: string }) {
return (
<div>
<h1>Results for:</h1>
<p>{query}</p>
</div>
);
}How Hackers Exploit It
Attackers craft URLs containing script tags or event handlers and trick victims into clicking them. For stored XSS, the malicious payload is saved in a database and served to every user who views the affected page. The injected script can steal session cookies, redirect users to phishing pages, or modify the page content to capture credentials.
How to Fix It
In React and Next.js, rely on JSX auto-escaping and avoid dangerouslySetInnerHTML. When you must render HTML, sanitize it with a library like DOMPurify. Set a strict Content-Security-Policy header that blocks inline scripts. Use HttpOnly and Secure flags on session cookies to limit the impact of any successful XSS.