Prevent XSS Attacks in React.js
prevent XSS attacks

Prevent XSS Attacks in React.js

Imagine that we have a blog variable that contains some HTML tags.

If we display the blog directly inside the JSX codes, we won't get the desired result. All HTML tags will be visible to the end users:

HTML tags

To solve this issue, React allows us to use a prop called dangerouslySetInnerHTML. You can pass this prop to HTML tags like div. It takes in an object with a key _html whose value is the HTML tags we want to render inside the container:

<div dangerouslySetInnerHTML={{__html:blog}}>

As you can see in the below image, all tags are rendered properly on the DOM:

Rendered HTML tags

But, in this case, we are likely to have an XSS vulnerability in our application, and the attacker could inject some malicious scripts inside the blog variable (for instance, script tag).

For more information, please visit the React.js official article:

https://legacy.reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml

To prevent our React applications, we should sanitize the html tags, before rendering them on the DOM. Fortunately, there are several libraries that sanitize the data. One of the top is DOMPurify. As you can see in the attached image, DOM-Purify has more than 4M weekly downloads.

For more information:

https://www.npmjs.com/package/dompurify

This library can be installed easily by just running the follwing command in the terminal:

*npm i dompurify

Then, in the react component, we need to import the DOMPurify library:

*import DOMPurify from 'dompurify';

Next, as below, we should sanitize the blog variable:

*const sanitizedBlog = DOMPurify.sanitize(blog);

And finally, in the dangerouslySetInnerHTML attribute, we just need to use the saniziedBlog:

<div dangerouslySetInnerHTML={{__html: sanitizedBlog}}>

</div>

DOMPURIFY LIBRARY

In this way, we could purify (sanitize) the data that has html elements in it.

XSS is one of the most common application vulnerabilities that has existed for a long time.

If you find this article useful, please leave your comments and likes and share it with your connections.

#xss_attack #react_security #dom_purify #html_tag


Mohammad Alshoker

Junior Front-End Web Developer

6 个月

That is Great .... Thanks for sharing ??

回复
K. Jermiel KOUNOUHO

Systems Solutions Architect Apprentice

8 个月

thanks too much for sharing

回复
Alireza Mohammadi

Front-End Developer

10 个月

Thank you for sharing

Amin Darabnia

Software Engineer | Front End Engineer | JavaScript,Tyepscript | React Js,Next Js

10 个月

Thanks ehsan

要查看或添加评论,请登录

社区洞察

其他会员也浏览了