- Always validate all variables and escape or sanitize them to protect against threats.
- Treat all untrusted data as text and not as JavaScript or HTML.
- Use HTML sanitization to remove dangerous HTML from a variable and return a safe HTML string. OWASP recommends using DOMPurify for HTML sanitization.
- Use output encoding when you need to safely display data exactly as a user typed it.
- Consider adding JavaScript encoding to untrusted data, but be cautious as it may alter the application’s functionality.
Helpful materials
- You can secure the application from XSS in many other ways by following the techniques in the Cross Site Scripting Prevention Cheat Sheet.
- It’s also important to protect user data by enforcing a Content-Security-Policy. You can achieve this in various ways, as described in the Content Security Policy Cheat Sheet.