Home > Software design >  React: dangerouslySetInnerHTML
React: dangerouslySetInnerHTML

Time:09-03

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

CodePudding user response:

When the HTML comes from any API is when it's most dangerous to use dangerouslySetInnerHTML.

This is covered in the docs:

In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack.

Essentially, the issue is that if your server doesn't properly sanitise user input, you open your site up to attacks that React protects you from by default. For example, lets say you allow users to write comments on your website, and your API sends back those comments in HTML. If a user writes a comment like e.g.

my comment <img src="./404" one rror="alert('test')" />

then e.g. that JavaScript code might be executed whenever someone else views that comment, unless you remember to protect against that when processing the comments.


I'd recommend returning your data from your API in a different format (e.g. JSON), and then processing it into React elements on the frontend.

CodePudding user response:

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.

  • Related