Encode output for its context, add a strict Content Security Policy, and limit what an attack can reach.
XSS (cross-site scripting) is when untrusted data runs as script in your users' browsers.
Contextual output encoding is the main defence:
- Use templates that escape output by default.
- Encode for the right context: HTML body, attribute, JavaScript or URL.
- Avoid helpers that output raw HTML.
- Never build HTML by joining strings.
- When users must submit rich HTML, sanitise it with a trusted library like DOMPurify, with an allowlist of tags and attributes.
Content Security Policy (CSP) adds a second layer. A strict policy blocks most injected script even when you miss some encoding. It should have:
- nonces or hashes for scripts
- no
'unsafe-inline' object-src 'none'
Limit the damage:
- Use
HttpOnlysession cookies, so scripts can't read them. - Send correct
Content-Typeheaders plusX-Content-Type-Options: nosniff. - Validate URLs and reject
javascript:links.
Input validation helps, but it doesn't replace output encoding.
- Encode output for its context, and use templates that escape by default.
- Sanitise rich HTML with an allowlist library.
- Use a strict CSP with nonces or hashes.
- Use HttpOnly cookies, nosniff and the correct Content-Type.
- Reject javascript: URLs.
Read more