Security operations

OWASP Cross-Site Scripting Prevention Cheat Sheet Explained

OWASP's XSS Prevention Cheat Sheet boils down to one idea: treat untrusted data as text, never as code. Here are the rules, the encoding for each context, and the defenses that back them up.

Cysoro Security TeamPublished · 12 min read
<div> user input </div><script> alert(1) </script>textContent = safe text Encode by context SECURITY OPERATIONS OWASP XSSprevention Data is text, never code.
Quick answer

The OWASP Cross-Site Scripting Prevention Cheat Sheet is OWASP's practical guide to stopping XSS, the flaw where untrusted data is treated as code in a victim's browser. Its core advice is to use a modern framework with auto-escaping, apply context-specific output encoding, sanitize any HTML you must accept, use safe DOM sinks, and add Content Security Policy as defense in depth.

Key takeaways

  • XSS happens when untrusted data reaches a page and the browser treats it as code, so every insertion point needs protection.
  • Encoding must match the context: HTML, attribute, JavaScript, CSS and URL contexts each need different encoding.
  • No single control stops XSS; combine frameworks, encoding, sanitization, safe sinks, CSP and testing.

Cross-site scripting is one of the oldest web flaws, and it is still one of the most common. The OWASP Cross-Site Scripting Prevention Cheat Sheet exists because the fix is not one trick: it is a set of habits that cover every place untrusted data can reach a page.

What is the OWASP XSS Prevention Cheat Sheet?

The OWASP XSS Prevention Cheat Sheet is a practical guide from the OWASP Cheat Sheet Series that shows developers how to prevent cross-site scripting. It covers framework protections, output encoding for each context, HTML sanitization, safe DOM sinks, and extra controls such as Content Security Policy.

OWASP describes XSS as a misnomer. The name came from early attacks that stole data across sites, but the term now covers injecting almost any content into a page. An attack can lead to account impersonation, stolen session cookies, observing user behavior, loading external content, and stealing sensitive data.

The cheat sheet is explicit about one point: no single technique will solve XSS. You need the right combination of defenses, applied everywhere untrusted data is added to a page. That matters because, as OWASP puts it, protecting 99 places and missing one still leaves you vulnerable.

This article walks through the cheat sheet in plain English, with the rules, a worked example, a checklist, and the mistakes OWASP warns against. It is written for developers, team leads, and small-business owners who run a website and want to know what good looks like.

What is cross-site scripting?

Cross-site scripting, or XSS, happens when 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.

Untrusted data is anything your application did not create itself. That includes form input, URL parameters, data stored by other users, and responses from other services. Even data from your own database counts as untrusted if a user supplied it earlier.

XSS is classified as CWE-79, improper neutralization of input during web page generation, as Precursor Security explains. In the OWASP Top 10 2021 it sits inside A03:2021 Injection, which covers injection flaws of all kinds. The injection category had about 274,000 occurrences in the data OWASP analyzed for that edition.

Once a script runs in a victim's browser, the attacker can do anything the victim can do through that browser on that site. That is why XSS is a serious flaw even when the payload looks small, such as a single script tag in a comment field.

What are the three main types of XSS?

The three main types are reflected, stored, and DOM-based XSS. They differ in where the malicious script lives and when it runs, but all three end with the victim's browser executing attacker-controlled code.

TypeWhere the script livesWho it hitsTypical example
Reflected XSSIn a request, such as a link or search termAnyone who clicks the crafted linkA search page echoes the query without encoding
Stored XSSSaved on the server, such as in a comment or profileEvery visitor who views the stored contentA malicious comment runs for all readers
DOM-based XSSIn the browser, in JavaScript that writes to the pageAnyone whose browser runs the unsafe codeA script copies part of the URL into the page with innerHTML
Mutation XSSIn HTML that the browser changes as it parses itVisitors to pages that re-serialize HTMLSanitized HTML is mutated into an executable form

Reflected XSS

Reflected XSS is the most familiar form. The attacker crafts a link containing a script, the victim clicks it, and the server reflects the input back in the response without encoding it. The script then runs in the victim's browser.

Stored XSS

Stored XSS, also called persistent XSS, is more damaging because the payload is saved. A malicious comment, forum post, or profile field is stored in the database and served to every later visitor. One injection can affect many people over a long period.

DOM-based XSS

DOM-based XSS never leaves the browser. JavaScript on the page reads untrusted data, for example from the URL fragment, and writes it into the document with an unsafe sink such as innerHTML or document.write. Server-side encoding alone cannot fix it, because the flaw is in client-side code.

OWASP has a separate DOM-based XSS Prevention Cheat Sheet for this type. If your application is a single-page app with heavy client-side rendering, that companion guide matters as much as this one.

What is the OWASP defense philosophy for XSS?

OWASP's philosophy is simple: every place where untrusted data is added to a page needs protection, and the protection must match how the data is used. Prefer safe APIs that treat data as text, encode for the specific context, and sanitize HTML only when you must accept it.

How untrusted data should reach the browser Untrusted dataforms, URLs,stored content Frameworkauto-escaping,templates Context encodingHTML, JS, URL,CSS, attribute Safe sinktextContent,createTextNode If you must accept HTML, sanitize it with a maintained library such as DOMPurify. Add Content Security Policy as a safety net, not as the main defense. Rule: data is text, never code
The OWASP pipeline for untrusted data: framework escaping, context encoding, sanitization where needed, and safe sinks. Illustration by Cysoro.

Coverage is what matters most. Many frameworks escape every value they render by default, whether it is trusted or not, and OWASP recommends that approach because it does not depend on deciding correctly which data is untrusted. A developer who guesses wrong about one field creates a hole.

Input validation can enforce expected formats, such as a number or an email address, but it does not replace these protections. A value that is valid input can still be dangerous when it is placed in the wrong context.

How do modern frameworks help prevent XSS?

Modern web frameworks reduce XSS bugs because they steer developers toward safe defaults: templating, auto-escaping, and safe rendering. When you use one correctly, most values are escaped before they reach the browser.

That protection has gaps, and the cheat sheet lists the common ones. React's dangerouslySetInnerHTML without sanitizing the HTML bypasses escaping. Angular's bypassSecurityTrustAs functions do the same. Lit's unsafeHTML, Polymer's innerHTML attribute, template injection, unvalidated URL values, and out-of-date plugins or components can all reintroduce risk.

When you use a framework, learn how it prevents XSS and where it has gaps. There will be times when you need to do something outside the protection it provides, and that is when output encoding and HTML sanitization become critical. OWASP is producing framework-specific cheat sheets for React, Vue, and Angular to cover those details.

The practical habit is to treat every escape hatch as a security review point. If a code review shows dangerouslySetInnerHTML or an equivalent, ask what is being inserted, where it came from, and whether it was sanitized. If nobody can answer, it should not ship.

What are the OWASP output encoding rules?

Output encoding converts untrusted input into a safe form so the browser displays it as data without executing it as code. The right encoding depends on the context, because browsers parse HTML, JavaScript, URLs, and CSS differently.

ContextWhere the data goesEncoding to useExample
HTML bodyBetween tags, such as inside a divHTML entity encoding< becomes &lt;
HTML attributeInside a quoted attribute valueAttribute encoding, value quotedAlways quote attribute values
JavaScriptInside a quoted string in a scriptEncoder for the JS and HTML script contextUse a maintained encoder, not manual escaping
CSSInside a style valueStrict validation or CSS hex encodingPrefer a fixed property with an allowlist value
URLAs a parameter value in a linkURL percent-encoding, then attribute encodingEncode each parameter, not the whole URL

HTML body context

For data between HTML tags, use HTML entity encoding. The characters to encode are & as &amp;, < as &lt;, > as &gt;, double quote as &quot;, and single quote as &#x27;. Most frameworks and encoding libraries do this for you.

When displaying text with JavaScript, assign it to the textContent property of an ordinary element such as a div. That creates a text node without parsing HTML, so the value cannot become markup.

HTML attribute context

For data in an ordinary text attribute such as title or value, use HTML attribute encoding and always surround the value with double or single quotes. Keep element and attribute names fixed, and never let untrusted data choose them.

Attribute encoding alone does not protect JavaScript in an event-handler attribute, because the HTML parser decodes character references before the JavaScript is interpreted. Prefer addEventListener with a trusted handler function and pass user values as data instead.

JavaScript context

When a server template inserts string data into an inline script, use an encoder documented for both the JavaScript string and the enclosing HTML script context. Do not insert untrusted code, identifiers, or expressions, and do not rely on escaping quotes by hand.

These encoders protect where the string is placed, not what happens next. Passing the result to eval or another code-interpreting function is still unsafe. For JSON, check that the Content-Type header is application/json and not text/html, so the browser does not treat the response as a page.

CSS and URL contexts

Do not interpolate untrusted data directly into CSS source, including selectors, property names, or declaration blocks. When dynamic styling is needed, use a CSSOM API such as element.style.setProperty with a fixed property name and a value constrained by an allowlist for that property.

For URLs, use URL encoding for parameter values, with percent-encoding. When a URL also goes into an href or src attribute, apply URL encoding first, then HTML attribute encoding. When building a URL in JavaScript, use encodeURIComponent for each untrusted query parameter value.

Which contexts should never hold untrusted data?

Some places in a page are dangerous contexts: output encoding will not make them safe, so untrusted data should never go there. OWASP lists directly inside a script block, inside an HTML comment, directly inside CSS, as a tag name, and as an attribute name.

Other risky areas include callback functions, URLs handled in code such as a CSS background URL with a javascript scheme, untrusted event-handler code such as a whole onclick value, and unsafe JavaScript functions such as eval, setInterval, and setTimeout with string arguments.

If your design needs a value in one of these places, change the design. Use a fixed set of allowed values, pass the value as data to a trusted function, or move the logic to the server. Trying to encode your way out of a dangerous context is a losing game, and the cheat sheet is blunt about that.

A related habit is to keep attribute names and tag names fixed. If user input chooses the element or the attribute, an attacker can pick a script element or an event-handler attribute and bypass your encoding entirely.

When should you sanitize HTML, and what are safe sinks?

When users need to author HTML, for example in a rich-text editor, output encoding would break the feature because the styling would not render. In those cases, use HTML sanitization: strip dangerous HTML from the value and return a safe string of HTML.

OWASP recommends DOMPurify for HTML sanitization, with code such as DOMPurify.sanitize(dirty). Do not write your own sanitizer. Browsers change, bypasses are found regularly, and a maintained library is patched when they are. Patch your sanitizer promptly, and do not modify the content after sanitizing it, because that can undo the protection.

Unsafe sinks vs safe sinks Avoid with untrusted data innerHTMLdocument.writeeval and string setTimeoutdangerouslySetInnerHTMLonclick with user code These treat data as code. Safe sinks textContentcreateTextNodeinsertAdjacentTextsetAttribute with fixed nameform field value These treat data as text.
Refactor unsafe sinks to safe sinks wherever untrusted data reaches the page. Illustration by Cysoro.

Safe sinks are places where a variable can be placed and treated as text, never executed. OWASP lists textContent, insertAdjacentText, className, setAttribute with a safe name, a form field value, and createTextNode. Refactor code to use these instead of innerHTML wherever you can.

One caution: document.createElement is not a text sink, because its argument selects the element name. Use a constant or an allowlist for that name, and never pass untrusted input directly. A dynamically created script element can execute when later code populates and inserts it.

What extra controls add defense in depth?

Framework protections, output encoding, and sanitization provide the best protection, and OWASP recommends them in all circumstances. The controls below add depth, but none of them replaces the core defenses.

  • Cookie attributes: HttpOnly, Secure, and SameSite limit how JavaScript and browsers interact with cookies. They limit the impact of an XSS attack but do not prevent script execution or fix the root cause.
  • Content Security Policy: an allowlist that controls which content can load. It is easy to get wrong, so use it as an additional layer and customize it for each application rather than deploying one blanket policy.
  • Trusted Types: where supported, enforce Trusted Types with the require-trusted-types-for script directive, so covered DOM sinks reject plain strings and require typed values created through policies.
  • Web Application Firewall: a WAF adds a layer, but it cannot reliably prevent all XSS attacks or fix vulnerable code, and it may miss DOM-based XSS that happens entirely in the browser.

Check your own site's headers with the free security headers checker to see whether CSP and related headers are present and well formed. A missing CSP is not proof of an XSS flaw, but a strict, working CSP is a useful safety net when encoding fails.

Also confirm that your site serves pages over HTTPS with a valid certificate, using the free SSL checker. HTTPS does not stop XSS, but it stops attackers on the network from injecting content into your pages in transit.

What mistakes does OWASP warn against?

OWASP calls out two common anti-patterns that still appear in old forum posts and modern advice: sole reliance on CSP headers, and reliance on HTTP interceptors or filters to do encoding for the whole application.

A blanket CSP for an entire organization assumes every browser supports every CSP feature equally, which is not true, and it tends to break legacy applications. The business then pushes back, exceptions are issued, and the cracks stay. CSP works best when it is customized for each application and used as defense in depth.

An HTTP interceptor, such as a servlet filter that encodes request parameters, cannot know the context in which each value will be rendered. The same parameter might appear between HTML tags on one page and inside a JavaScript block on another, where HTML encoding is not enough. Interceptors also miss DOM-based XSS and data from internal services.

The fix OWASP recommends is to encode as close as possible to where the data is rendered, where the context is known. That is more work than a single filter, but it covers the cases a filter cannot see. Our guide to spear phishing shows a different attack that also exploits trust, and the same lesson applies: fix the root cause.

How do you apply the cheat sheet? A checklist

Use this checklist on a new feature or during a security review. If you cannot tick every box, note the gap and plan the fix before the feature ships.

OWASP XSS prevention checklist 1. Use a modern framework and keep it patched 2. Audit every escape hatch, such as dangerouslySetInnerHTML 3. Encode every value for its output context 4. Never place untrusted data in a dangerous context 5. Sanitize HTML you must accept, with DOMPurify 6. Use safe sinks: textContent, not innerHTML 7. Add CSP and cookie flags, then test every context
Seven steps that turn the OWASP cheat sheet into a review checklist. Illustration by Cysoro.
  1. Inventory every place untrusted data reaches a page, including templates, API responses, and client-side rendering.
  2. Confirm the framework's default escaping is on and that no template disables it without a review.
  3. Encode for the context, not with one generic function, and quote every attribute value.
  4. Sanitize rich HTML with a maintained library, and patch that library when updates appear.
  5. Replace unsafe sinks with textContent, createTextNode, and addEventListener.
  6. Set cookie flags (HttpOnly, Secure, SameSite) and a per-application CSP.
  7. Test with a scanner and manual review, and retest after every change to rendering code.

For a wider review of your site's defenses, see our small business cybersecurity checklist, which covers updates, backups, and access controls alongside web security.

The bottom line

The OWASP XSS Prevention Cheat Sheet is not a single rule to memorize. It is a discipline: treat untrusted data as text, encode it for the context where it appears, sanitize the HTML you must accept, and use safe sinks in the browser.

Start with your framework's defaults, audit the escape hatches, and add CSP as a safety net. You can check the headers your site actually sends today with the free security headers checker, then work through the checklist above one page at a time.

Frequently asked questions

What is the OWASP XSS Prevention Cheat Sheet?

It is OWASP's practical guide to preventing cross-site scripting. It explains how XSS happens, which places in a page are safe for untrusted data, how to encode data for each output context, and which extra controls add defense in depth.

What is cross-site scripting in simple terms?

Cross-site scripting, or XSS, is a flaw where an attacker gets a website to include malicious script in a page shown to another user. When that user opens the page, the script runs in their browser as if the site itself sent it.

What are the three main types of XSS?

Reflected XSS sends a malicious script in a request, such as a link, and the server reflects it back in the response. Stored XSS saves the script on the server, for example in a comment, so it runs for every visitor. DOM-based XSS happens entirely in the browser when JavaScript writes untrusted data into the page unsafely.

Is input validation enough to prevent XSS?

No. Input validation helps by rejecting data that does not match the expected format, but it does not replace output encoding. OWASP is clear that validation is a supporting control, not the main defense, because the same value can be safe in one context and dangerous in another.

Does a Content Security Policy stop XSS?

Not on its own. A Content Security Policy can limit the damage when encoding fails, by blocking inline scripts and untrusted sources, but it is a defense-in-depth layer. OWASP warns against relying on CSP alone, and against one blanket policy for a whole organization.

What is the safest way to display user input in JavaScript?

Use a safe sink such as textContent or createTextNode, which treats the value as text and never parses it as HTML. Avoid innerHTML, document.write and eval with untrusted data. If you must accept HTML, sanitize it with a maintained library such as DOMPurify.

What does OWASP say about dangerous contexts for XSS?

OWASP lists places where untrusted data should never go, even with encoding, including directly inside a script block, inside an HTML comment, directly inside CSS, and as a tag or attribute name. These contexts have no safe encoding, so the design must avoid them.

How do I test whether my site is vulnerable to XSS?

Use a scanner such as OWASP ZAP, review code where untrusted data reaches the page, and test each output context with harmless payloads in a test environment. Also check your security headers and CSP, and fix the root cause in code rather than only blocking payloads at a firewall.

Sources

  1. OWASP Cheat Sheet Series — Cross Site Scripting Prevention
  2. Precursor Security — Cross-Site Scripting (XSS): Types, Examples, Prevention
  3. CyberDefenders — What Is Cross-Site Scripting (XSS)? Types and Defenses
Written & fact-checked byCysoro Security Team

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.

  • Email authentication
  • Phishing & BEC
  • Domain & DNS security
  • Small-business security

Checked against the OWASP Cross Site Scripting Prevention Cheat Sheet and OWASP Top 10 A03:2021 Injection guidance.

How we write and fact-check →

Free tools for this topic

No account needed.

See where your domain stands

Free for up to 3 domains. No card, no installs.

Start free