← Learn

Definition

What is cross-site scripting (XSS)?

Cross-site scripting (XSS) is a vulnerability where an attacker gets their own JavaScript to run in another user's browser through your site. Because the script runs in the victim's session, it can steal their tokens, act as them, or rewrite the page. It happens when your app renders user-controlled content as HTML or script without escaping it.

How it happens

If your app takes user input, a comment, a name, a URL, and puts it into the page as raw HTML, an attacker can include a script or an event handler that the browser executes. In React, this most often comes from dangerouslySetInnerHTML with unsanitized content.

How to prevent it

Render user content as text so the framework escapes it, and if you must inject HTML, sanitize it first with a library like DOMPurify. A Content-Security-Policy header adds a strong second layer by limiting which scripts the browser will run.

What this means for AI-generated code

AI-generated code introduces XSS when it renders content from an API or a user as HTML to make it display, without sanitizing it. The code works and looks correct, so the vulnerability ships unnoticed until someone sends a payload.

Want to know if your app has this issue? Scan a public repo free, no account needed.

Scan a repo →

Related: fix an XSS in React

What Is Cross-Site Scripting (XSS)? Explained Simply: Prbl