0

I'm displaying user comments on react with DomPurify. When the user enters a dangerous strings: eg ' it gets encoded, how can I safely decode it?

Encoded string react

Here is the code:

 <p className="donor-comment">
    {DOMPurify.sanitize(hit.comment)}
 </p>

Thanks in advance

Mendi Sterenfeld
  • 378
  • 5
  • 26
  • Why do you want to decode it again? You can take the encoded string and display it via `dangerouslySetInnerHTML` prop. – Silvan Bregy Feb 17 '22 at 14:23
  • Decode it again? what do you mean by that? isn't `dangerouslySetInnerHTML` dangerous? – Mendi Sterenfeld Feb 17 '22 at 14:26
  • What do you exactly want to do with the string? display it Or what else? – Silvan Bregy Feb 17 '22 at 14:28
  • @SilvanBregy This is the current display of the comment, which is retrieved from the DB. I want to safely display the original comment: `Without you nothing would be done, I'm happy to complete your goal` – Mendi Sterenfeld Feb 17 '22 at 14:32
  • 1
    OK. Since you do sanitise it using `DOMPurify.sanitize` you can directly display it using `dangerouslySetInnerHTML` . It is ofc dangerous but you prevent any danger since you sanitise it. That's the idea of the module – Silvan Bregy Feb 17 '22 at 14:34

1 Answers1

1

You don't have to escape user input manually or by using third-party libs like DOMPurify. React DOM does it by default.

https://reactjs.org/docs/introducing-jsx.html#jsx-prevents-injection-attacks

By default, React DOM escapes any values embedded in JSX before rendering them. Thus it ensures that you can never inject anything that’s not explicitly written in your application. Everything is converted to a string before being rendered. This helps prevent XSS (cross-site-scripting) attacks.

is2ei
  • 51
  • 4