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:
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:
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:
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:
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>
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
Junior Front-End Web Developer
6 个月That is Great .... Thanks for sharing ??
Systems Solutions Architect Apprentice
8 个月thanks too much for sharing
Front-End Developer
10 个月Thank you for sharing
Software Engineer | Front End Engineer | JavaScript,Tyepscript | React Js,Next Js
10 个月Thanks ehsan