Defense and mitigation

A proper sanitization of users input both front-end and back-end is the key to prevent XSS. The addition of multiple defense solutions in all fronts is what can make our web application well hardened against XSS.

Input sanitization

Use existing library to sanitize and escape users inputs such as:

Use encoding functions/libraries for special characters such as:

  • htmlspecialchars (PHP)

  • htmlentities (PHP)

  • html-entities (NodeJS)

Code Coding Practices

Avoid using JS functions that modify HTML text directly.

  • DOM.innerHTML

  • DOM.outerHTML

  • document.write()

  • document.writeln()

  • document.domain

Some jQuery functions might also lead to XSS:

  • html()

  • parseHTML()

  • add()

  • append()

  • prepend()

  • after()

  • insertAfter()

  • before()

  • insertBefore()

  • replaceAll()

  • replaceWith()

Server configurations

Some servers configuration can help to prevent XSS. For example, it is recommended to implement:

  • CSP header

  • HTTPOnly and Secure (to protect cookie stealing)

  • Using HTTPS

  • a WAF

  • using a framework that includes built-in protection against XSS (ex: ASP.NET)

Last updated