- 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 is also important to protect user data by enforcing a Content-Security-Policy. This can be achieved in various ways as described in the Content Security Policy Cheat Sheet.