javascriptreactjsdangerouslysetinnerhtml

React: dangerouslySetInnerHTML


I've question about dangerouslySetInnerHTML, is it dangerous to use it, when the html comes from my api or there is no difference and maybe attacked anyway? Thanks


Solution

  • DangerouslySetInnerHTML

    Yes, there's potential concern. Although, you'll gain some extra performance, since react doesn't compare the dangerouslySetInnerHTML field with Virtual DOM.

    HOW EXACTLTY IT'S DANGEROUS?

    If user add some malicious code into the comments / other inputs and this data renders on the dangerouslySetInnerHTML field via API, your application deal with XSS Attack ([https://owasp.org/www-community/attacks/xss/][1]).

    HOW CAN POTENTIAL XSS BE PREVENTED?

    Based on the best practices, it's best to sanitize the dangerouslySetInnerHTML element with some external modules like: DOMPurify (https://github.com/cure53/DOMPurify). It will remove/filter out the potentially malicious code from the HTML and prevent XSS.