ShieldX Toolly
Open a tool Donate
Home Home
Blog Blog
FAQ FAQ
Open a tool Donate
Back to cheatsheets
Developer

XSS Prevention

Prevent Cross-Site Scripting with output encoding, HTML sanitization, and CSP.

3 snippets Intermediate
XSSoutput encodingDOMPurifyCSPsanitization

What you'll learn

  • Context-aware output encoding
  • HTML sanitization with DOMPurify
  • Safe DOM manipulation

How to use these snippets

  1. Click the Copy button next to any snippet to copy it to your clipboard.
  2. Paste the code into your project, IDE, or terminal.
  3. Replace placeholder values (like example.com or your-secret) with your actual data.
  4. Review the code comments for important security notes and caveats.
Code Snippets

Copy-paste code snippets

3 ready-to-use snippets for xss prevention. Click copy and paste into your project.

Context-aware output encoding
                // HTML context
function encodeHTML(str) {
  return str
    .replace(/&/g, '&')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#x27;');
}

// URL context (for href/src attributes)
function encodeURL(str) {
  return encodeURIComponent(str);
}

// JavaScript context (for inline JS strings)
function encodeJS(str) {
  return str
    .replace(/\\/g, '\\\\')
    .replace(/'/g, "\\'")
    .replace(/"/g, '\\"')
    .replace(/\n/g, '\\n')
    .replace(/\r/g, '\\r')
    .replace(/</g, '\\u003c');
}
              
HTML sanitization with DOMPurify
                // Install: npm install dompurify
import DOMPurify from 'dompurify';

const clean = DOMPurify.sanitize(userInput, {
  ALLOWED_TAGS: ['p', 'br', 'strong', 'em', 'ul', 'ol', 'li', 'a'],
  ALLOWED_ATTR: ['href', 'title'],
  ALLOW_DATA_ATTR: false,
});

// For React: use dangerouslySetInnerHTML only after sanitizing
// <div dangerouslySetInnerHTML={{__html: clean}} />
              
Safe DOM manipulation
                // ❌ Never do this
element.innerHTML = userInput;  // XSS!

// ✅ Use textContent for plain text
element.textContent = userInput;

// ✅ Use DOMPurify for HTML
element.innerHTML = DOMPurify.sanitize(userInput);

// ✅ Safe attribute setting
element.setAttribute('href', sanitizeUrl(url));
// Never use user input in:
// - eval()
// - setTimeout/setInterval with string
// - document.write()
// - innerHTML / outerHTML
              
100% Free · No signup · No cost

Generate something unguessable right now

148 bits of entropy, a crack-time estimate you can trust, and a clipboard that clears itself after 30 seconds.

Open the toolkit

Part of the Toolly ecosystem · secure.toolly.site