Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe alternative to dangerouslySetInnerHTML

Tags:

reactjs

I would like to have a dynamic blog on my site (which uses React). Initially, I was going to store the posts in raw HTML in my database and generate the content using dangerouslySetInnerHTML. I am however concerned about the security implications. While my app doesn't have any sensitive data, I'm not well enough versed in XSS to know all the dangers I'd be opening my app up to.

I'm curious if there's a performant, safe way to dynamically load blog pages within my app. Would using https://github.com/odysseyscience/react-router-proxy-loader be useful in this case? Have a folder of blog post JSX separate from the rest of my app and load it using this (admittedly, I'm not sure how react-router-proxy-loader works).

I'm open to suggestions.

like image 709
Kevin Avatar asked Mar 14 '15 01:03

Kevin


People also ask

Should I avoid dangerouslySetInnerHTML?

Dynamically rendering benign HTML code in React requires the use of dangerouslySetInnerHTML . That is not a naming mistake. This property is dangerous, and using it carelessly will create XSS vulnerabilities in your application.

Is it safe to use dangerouslySetInnerHTML?

The Dangers of DangerouslySetInnerHTMLIt is not safe to simply add your HTML code as this is prone to Cross Site Scripting or XSS attacks for short. XSS attack is a type of security vulnerability where attackers inject code client-side to steal information and perform malicious scripts in the app.

What to use instead of innerHTML in React?

According to the official documentation, dangerouslySetInnerHTML is React's replacement for using innerHTML in the browser DOM. This means that if in React if you have to set HTML programmatically or from an external source, you would have to use dangerouslySetInnerHTML instead of traditional innerHTML in Javascript.

How do I convert HTML to JSX?

You can use https://magic.reactjs.net/htmltojsx.htm which is an online HTML to JSX compiler. Show activity on this post. You can also use https://transform.tools/html-to-jsx beside https://magic.reactjs.net/htmltojsx.htm as mentioned above. Show activity on this post.


1 Answers

If XSS is your primary concern, you can use DOMPurify to sanitize your HTML before inserting it in the DOM via dangerouslySetInnerHTML. It's just 10K minified. And it works in Node too.

like image 170
Alexandre Kirszenberg Avatar answered Oct 13 '22 21:10

Alexandre Kirszenberg