Prevent cross-site scripting by encoding untrusted data for the exact context where it is displayed, using a modern framework's automatic escaping, sanitizing any HTML users are allowed to submit with a maintained library like DOMPurify, and adding a strict nonce-based Content Security Policy as a safety net. No single control is enough: OWASP is explicit that XSS needs layered defenses.
Key takeaways
- XSS happens when untrusted data reaches a page and the browser treats it as code — encoding by output context is the core fix.
- Modern frameworks escape output by default; most XSS bugs come from escape hatches like dangerouslySetInnerHTML or unvalidated URLs.
- A strict nonce-based Content Security Policy blocks injected scripts even when encoding fails, but it is a backup, not a replacement.
Cross-site scripting is one of the oldest web attacks, and it is still one of the most common. It does not break into your server. It turns your own website into the delivery mechanism for an attack on your visitors.
What is cross-site scripting?
Cross-site scripting (XSS) is an injection attack in which malicious scripts are injected into a website and then run in another user's browser, with the privileges of the trusted site.
The name is a misnomer from the early days of the attack, when it mostly involved stealing data across sites. Today it covers any case where an application puts untrusted data into a page in a way that lets the browser treat it as code. A comment that should appear as plain text instead runs as JavaScript, or adds HTML the attacker controls.
OWASP merged XSS into the Injection category (A03:2021) in the 2021 Top 10, because it is injection into the browser's HTML and JavaScript context. In OWASP's 2021 data, the Injection category had 274,228 occurrences across the applications tested, making it one of the most widespread weaknesses in web software. The weakness itself is tracked as CWE-79: improper neutralization of input during web page generation.
Once a script runs in a victim's browser, it can read session cookies, rewrite page content, capture keystrokes, or perform actions as the victim — posting, transferring money or changing settings — without the victim noticing anything wrong.
How does an XSS attack work?
An XSS attack has three ingredients: untrusted data, a page that renders it without encoding, and a victim who loads the page while logged in.
Take a comment box. A visitor writes a normal comment, and the site stores it. An attacker writes a comment containing a script tag instead. When the next visitor loads the page, the server sends the attacker's comment as part of the page, and the browser runs the script as if the site itself had written it. That is stored XSS, and one payload can reach every visitor.
Reflected XSS works through a link. The attacker crafts a search URL containing a script, and sends it to a victim. The site echoes the search term back onto the results page without encoding it, and the victim's browser runs the script. DOM-based XSS is similar, except the payload never touches the server: JavaScript on the page reads data from the URL or another source and writes it into the page unsafely.
Two real cases show the range. In 2005, the Samy worm used stored XSS on MySpace to add over a million friends to one profile in less than a day, spreading itself from profile to profile. In 2014, a stored XSS flaw in TweetDeck let a single tweet execute JavaScript that retweeted itself from every account that saw it. Both were fixed quickly, but both show how fast a single payload can spread.
How do you prevent XSS with output encoding?
Output encoding is the core defense: convert dangerous characters into safe representations before untrusted data is rendered, using the encoding that matches the exact context where the data lands.
The key insight is that encoding must match the context. Data that is safe in an HTML body is not safe in a JavaScript string, a URL or a style attribute, because the browser parses each context differently. OWASP's cheat sheet puts it plainly: use the right encoding for the right place, and never put untrusted data in a place that has no safe encoding at all.
| Output context | What to do | Example |
|---|---|---|
| HTML body | HTML-entity encode | & < > " ' become entities |
| HTML attribute | Attribute-encode, always quote the value | <input value="ENCODED"> |
| JavaScript data | JavaScript-encode for the string and the enclosing HTML | Use a documented encoder, not manual escaping |
| URL parameter | Percent-encode with encodeURIComponent() | Encode each value, not the whole URL |
| CSS value | Hex-encode, or avoid user data in CSS entirely | Prefer setProperty() with an allowlist |
| JSON response | Set Content-Type: application/json | Never serve JSON as text/html |
Some places are dangerous contexts with no safe encoding: directly inside a script block, inside an HTML comment, directly in CSS, as a tag name or attribute name, or inside event-handler code. Do not place variables there at all. Use safe sinks instead: assign untrusted text with textContent, set attributes with setAttribute() using a fixed name, and create text nodes with createTextNode(). The OWASP XSS Prevention Cheat Sheet lists these rules in full.
Do not write your own encoding library. Use an established one: the OWASP Java Encoder for Java, the Microsoft AntiXSS library for .NET, or your framework's built-in encoder. Hand-rolled escaping is where most XSS bugs are born.
What do modern frameworks do to prevent XSS?
Modern frameworks do most of the encoding for you, which is why applications built on them have far fewer XSS bugs than hand-rolled templates.
React, Vue, Angular and Django all escape interpolated values automatically. In React, {userComment} in JSX is escaped before it reaches the page. In Django templates, variables are auto-escaped by default. That default is your best protection, and you should only step outside it deliberately, never by habit.
The bugs come from the escape hatches. React's dangerouslySetInnerHTML, Angular's bypassSecurityTrustAs* functions and Lit's unsafeHTML all let raw HTML through, and each one is an XSS hole unless the HTML is sanitized first. Unvalidated URL values are another gap: React 19 blocks javascript: URLs in src and href, but that does not replace validating URLs for your application.
Audit your codebase for these escape hatches regularly. Every one should have a comment explaining why it is safe, and ideally a sanitizer in front of it. If you cannot explain why a particular dangerouslySetInnerHTML is safe, remove it.
How do you sanitize HTML users are allowed to submit?
Sometimes encoding is not enough, because the user is supposed to submit HTML — a formatted comment, a rich-text post, or content from a WYSIWYG editor. Encoding would break the formatting, so you sanitize instead.
HTML sanitization strips dangerous markup from user input and returns safe HTML. OWASP recommends DOMPurify for client-side JavaScript sanitization, and it is the standard choice:
const clean = DOMPurify.sanitize(dirty);
Three rules make sanitization work. First, sanitize once, at the point of use, and do not modify the string afterwards — changing it can undo the sanitizer's work. Second, check that no library downstream mutates the string before it reaches the page. Third, keep the sanitizer patched: browsers change, and bypasses are discovered regularly, so an old DOMPurify version is a vulnerability.
On the server, use a maintained sanitizer for your stack, such as OWASP Java HTML Sanitizer for Java or Bleach-style allowlist sanitizers for Python. The principle is the same everywhere: allow only the tags and attributes you need, and strip everything else.
How does a Content Security Policy stop XSS?
A Content Security Policy (CSP) is an HTTP header that tells the browser which scripts and resources are allowed to load. Even if an attacker injects a script, a strict CSP can stop it from executing.
By controlling resource loads, a CSP can block inline script tags, inline event handlers, javascript: URLs and eval(). A strict, nonce-based policy looks like this:
Content-Security-Policy: script-src 'nonce-{random}' 'strict-dynamic'; object-src 'none'; base-uri 'self';
The server generates a random nonce for each response and adds it to every legitimate script tag. Any script without the right nonce is refused. The 'strict-dynamic' keyword lets trusted scripts load further scripts without each one needing its own nonce. Adding object-src 'none' blocks plugins, and base-uri 'self' stops attackers from redirecting relative URLs.
MDN is clear about the limits: a CSP is not a replacement for output encoding and sanitization. It is a defense-in-depth layer that protects you when encoding fails. Test a new policy with the Content-Security-Policy-Report-Only header first, so you can see what would break before you enforce it. You can check your own site's headers, including CSP, with our free security headers checker. The MDN guide to Content Security Policy walks through strict CSP setup in detail.
How do you test a site for XSS?
Testing for XSS means trying to break your own outputs, then watching what the browser does with the input. Do it in a test environment, never against a live site you do not own.
Start with the obvious places: search boxes, comment forms, profile fields, URL parameters and anywhere user data is reflected back onto a page. Try a harmless probe first, such as a unique string with angle brackets, and see whether it is encoded in the response. Then try standard payloads in each context: a script tag in a comment, an event handler in an attribute, and a javascript: URL in a link field.
Automate the routine checks. OWASP ZAP is a free scanner that finds reflected and stored XSS in common cases, and it fits into a CI pipeline. For DOM-based XSS, use a browser-based scanner or manual review of the JavaScript that writes to the page. Finally, watch your CSP violation reports: a spike in blocked scripts is often the first sign that someone is probing your site, or that a legitimate feature is broken.
Add two more habits to your process. First, run a header check on every deploy — our SSL checker confirms the transport layer while the headers checker confirms the CSP is actually present. Second, treat every new user-input field as a review point: who can write to it, where is it rendered, and what encoding applies?
What are the most common XSS mistakes?
The same five mistakes cause most XSS vulnerabilities. They are all avoidable.
- Using
innerHTMLwith untrusted data. This is the single most common cause of DOM-based XSS. UsetextContentinstead, and only useinnerHTMLwith sanitized HTML. - Encoding once, for the wrong context. HTML-encoding a value that lands inside a JavaScript string does not protect it. Encode for the context where the data actually lands.
- Trusting input validation. Validation enforces format; it does not neutralize code. An attacker can smuggle a payload past a validator that was never designed to be a security boundary.
- Leaving a CSP in report-only mode forever. A policy that only reports does not block anything. Move to enforcement once the reports are clean.
- Allowing
'unsafe-inline'in your CSP. This reopens the exact hole CSP exists to close. Use nonces or hashes instead, even though the refactor takes longer.
Another common mistake is forgetting cookies. Mark session cookies HttpOnly so JavaScript cannot read them, and set the Secure flag so they only travel over HTTPS. Neither flag stops XSS, but together they make a successful attack much less valuable. For a broader security routine, see our small business cybersecurity checklist.
What should you do if your site has an XSS vulnerability?
Act like it is already being exploited, because it may be. The fix is usually small, but the exposure window matters more than the patch.
First, confirm the flaw in a test environment and work out the blast radius: which pages render the untrusted data, and who can see them? Second, apply the encoding or sanitization fix and deploy it. Third, if the flaw was stored XSS on a public page, assume the payload reached visitors: invalidate affected sessions, review logs for unusual requests, and check for injected content in your database.
Fourth, tighten the CSP while you fix the root cause, so a second payload in the same place cannot execute. Fifth, tell affected users if their accounts or data were at risk, and document the fix. Finally, add a regression test for the exact payload, so the same bug cannot come back in a later release.
The bottom line
Preventing XSS is a discipline, not a product: encode output for its context, let your framework escape by default, sanitize HTML you must render, and back it all up with a strict Content Security Policy. OWASP's own warning is the summary — no single technique will solve XSS, so use the combination.
Start today with the two checks that cost nothing: run your site through the free security headers checker to see whether a CSP is present, and search your codebase for innerHTML and dangerouslySetInnerHTML. Fixing those two things closes most of the holes attackers actually use.
For ongoing website protection, see our website security platform.
Frequently asked questions
What is cross-site scripting in simple terms?
Cross-site scripting, or XSS, is an attack where a hacker gets a website to send malicious JavaScript to another person's browser. The script runs as if it came from the trusted site, so it can read cookies, change what the victim sees, or act on their behalf.
What is the difference between stored, reflected and DOM-based XSS?
Stored XSS saves the malicious script on the server, for example in a comment, and it runs for every visitor who loads the page. Reflected XSS bounces the script off the server in a single request, usually through a crafted link. DOM-based XSS never reaches the server: it is built and executed by JavaScript running in the victim's browser.
Can cross-site scripting steal passwords?
It can steal session cookies, which is often just as good as a password, because the cookie lets the attacker use the victim's logged-in session. It can also rewrite the login page to capture the password directly, or perform actions as the victim without them noticing.
Does HTTPS prevent cross-site scripting?
No. HTTPS encrypts traffic between the browser and the server, but an XSS payload travels inside that encrypted traffic like any other content. HTTPS stops attackers on the network from reading or changing your pages; XSS comes from your own application putting untrusted data into a page.
Is input validation enough to prevent XSS?
No. Input validation is useful for enforcing expected formats, like an email address or a date, but it does not replace output encoding. Attackers can encode payloads in ways validation misses, and some fields legitimately need characters like angle brackets. Always encode on output, whatever validation you did on input.
What is the easiest fix for XSS in an existing site?
Start with a strict Content Security Policy, because it can block injected scripts even before you fix every output. Then fix the outputs: use your framework's default escaping everywhere, replace innerHTML with textContent for untrusted data, and sanitize any HTML you must render with DOMPurify.
Sources
The engineers and analysts who build Cysoro's domain scanner, email-authentication checks and free security tools. We test what we write about every day — SPF, DKIM, DMARC, certificates, look-alike domains and phishing — and check each guide against the relevant standards, government guidance and vendor documentation.
Checked against the OWASP XSS Prevention Cheat Sheet, the OWASP Top 10 2021 and MDN's Content Security Policy documentation.
How we write and fact-check →