How to Get Cross-Site Scripting Right
A class of vulnerability, known as XSS, where an attacker gets malicious script to run in other users' browsers through content a site displays without proper handling.
On this page
The key figures
- Types
- stored, reflected and DOM-based
- Primary defense
- context-aware output encoding
- Additional defenses
- Content Security Policy and sanitizing HTML input
- OWASP Top 10
- injection, including XSS, is a listed risk category
Why this is worth getting right
XSS can steal sessions, deface pages and act on users' behalf, and it remains one of the most common web vulnerabilities.
Do this, not that
Do
- Encode output for the context it appears in
- Use framework templating that escapes by default
- Sanitize any user-provided HTML with a maintained library
- Deploy a Content Security Policy
- Test inputs that end up in pages, attributes and scripts
Don’t
- Inserting user input with innerHTML
- Disabling framework escaping
- Blocklist filters that miss variants
- Trusting data from your own database without encoding
When to bring in help
Our advice Bring in help when a security scan reports XSS, or when a site accepts rich text from users.
Where this comes from
- OWASP — Cross Site Scripting Prevention Cheat Sheet
- MDN Web Docs — Cross-site scripting (XSS)
The figures and practices above come from the sources listed.
Working on something like this?
We take on Web Design & Development work for teams who want it done once, properly. Tell us what you are building and we will tell you honestly whether we are the right studio for it. Start a project.
Where to go next
Spotted something wrong? Report an error on this page. We correct on the page and say what changed.