highCode Injection

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

Vulnerablecomponents/search-results.tsx
export default function SearchResults({ query }: { query: string }) {
  return (
    <div>
      <h1>Results for:</h1>
      <div dangerouslySetInnerHTML={{ __html: query }} />
    </div>
  );
}
Fixedcomponents/search-results.tsx
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.

Frequently Asked Questions

Does React automatically prevent XSS?
React escapes values embedded in JSX by default, which prevents most XSS. However, using dangerouslySetInnerHTML, creating elements from user-controlled props, or injecting into href attributes with javascript: URLs can still introduce XSS vulnerabilities.
What is the difference between stored and reflected XSS?
Reflected XSS payloads are included in a request (such as a URL parameter) and immediately echoed back in the response. Stored XSS payloads are saved on the server (in a database or file) and served to users later, making them more dangerous because they affect every visitor.
How does Content-Security-Policy help prevent XSS?
A strict CSP header tells the browser which script sources are allowed. By disallowing inline scripts and restricting sources to your own domain, CSP blocks injected scripts from executing even if an XSS vulnerability exists in the HTML.

Related Security Topics

Check Your Code for This Vulnerability

Run a free scan to check if your site is affected by cross-site scripting (xss).