Back to cheatsheets
Developer
XSS Prevention
Prevent Cross-Site Scripting with output encoding, HTML sanitization, and CSP.
What you'll learn
- Context-aware output encoding
- HTML sanitization with DOMPurify
- Safe DOM manipulation
How to use these snippets
- Click the Copy button next to any snippet to copy it to your clipboard.
- Paste the code into your project, IDE, or terminal.
- Replace placeholder values (like
example.comoryour-secret) with your actual data. - 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, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
// 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.
Part of the Toolly ecosystem · secure.toolly.site