Skip to content

XSS Prevention Deep Dive

Prevent Cross-Site Scripting with output encoding, DOMPurify, and Trusted Types.

What you'll learn

  • XSS types: stored, reflected, DOM-based
  • Output encoding: HTML, attribute, JS, URL context
  • DOMPurify for sanitizing untrusted HTML
  • Trusted Types as a strong XSS defense

Concept

XSS Prevention Deep Dive

Cross-Site Scripting (XSS) is the #1 web vulnerability, occurring when untrusted data is inserted into a page without encoding.

Three Types

Stored XSS: payload stored in DB, served to all visitors. Reflected XSS: payload in URL, reflected in response. DOM-based XSS: payload in URL, inserted into DOM by JS.

Output Encoding

Context-aware encoding: HTML (< becomes &lt;), attribute (quotes encoded), JS (< becomes \x3c), URL (encodeURIComponent). Frameworks like React auto-encode JSX expressions.

DOMPurify

When you must insert untrusted HTML, use DOMPurify.sanitize() to strip scripts, event handlers, javascript: URLs. Configure to allow only safe tags and attributes.

Trusted Types

Requires all DOM sink assignments (innerHTML, eval) to receive TrustedHTML object. Create a policy that sanitizes input. Any raw string assignment throws. Makes XSS impossible by construction.

Example

              function encodeHTML(s) { return s.replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c])); }
function sanitize(html) { return html.replace(/<script[\s\S]*?<\/script>/gi,'').replace(/on\w+\s*=\s*["'][^"']*["']/gi,'').replace(/javascript:/gi,''); }
const input = '<script>alert(1)</script>Hello';
console.log('Encoded:', encodeHTML(input));
console.log('Sanitized:', sanitize(input));
// Safe: element.textContent = input; // or DOMPurify.sanitize(input)
// Unsafe: element.innerHTML = input; // XSS!
            

encodeHTML escapes dangerous characters. sanitize strips scripts and handlers (simplified DOMPurify). React auto-encodes JSX expressions.

Try it

  • Hash Generator

    Hash user input for safe display - hashing prevents XSS by never showing raw input.

Common mistakes

The mistake

Using innerHTML with untrusted data.

The fix

innerHTML interprets value as HTML. Use textContent for text, or DOMPurify.sanitize() for HTML.

The mistake

Using dangerouslySetInnerHTML without sanitization.

The fix

Always sanitize with DOMPurify first: dangerouslySetInnerHTML={{__html: DOMPurify.sanitize(data)}}.

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors