Search code examples
javascriptreactjsxssgatsbysanitization

Sanitizers VS dangerouslySetInnerHtml


According to some React documentation:

Improper use of the innerHTML can open you up to a cross-site scripting (XSS) attack. Sanitizing user input for display is notoriously error-prone, and failure to properly sanitize is one of the leading causes of web vulnerabilities on the internet.

It seems that improper usage of the sanitizers and the innerHTML can expose the site XSS (Cross-Site Scripting) attacks.

On the other hand, according to other documentation (such as Gatsby or sanitizers itself), they are recommended:

The most straightforward way to prevent a XSS attack is to sanitize the innerHTML string before dangerously setting it. Fortunately, there are npm packages that can accomplish this; packages like sanitize-html and DOMPurify.

What's the best and safest approach to avoid exposing an application to XSS attacks in React while also avoiding improper usage of sanitizers?


Solution

  • I think the best, safest, and optimal approach, as it has been said through comments (especially by Corey Ward) is to avoid the usage of the dangerouslySetInnerHtml as long as it is possible prior to sanitizers. There are some amazing libraries such as markdown-to-jsx that extends the benefits of dangerouslySetInnerHtml (rendering HTML) without exposing the web to XSS attacks.

    If the only solution for the use-case is to usedangerouslySetInnerHtml, then the solution must be using sanitizers, keeping in mind that it should be configured to keep styles, classes, and other desired behavior to avoid losing changes.