XSS protection in React

First, let’s see what is XSS attack. An XSS attack is used to gain access to users browser by using vulnerabilities in the application. It is caused by Cross-site scripting. In simple words, It is the script being injected into a comment or URL, etc. between a poorly coded web page and the client's web browser. Non-persistent and persistent are two types of XSS attack.

React escapes string variables automatically and this prevents XSS injection through string HTML with malicious JavaScript. You pass a function with JSXas an event handler rather than a string. A typical attack like the one given below will not work.

 const username ="<img onerror='alert(\"Hacked!\")' src='invalid-image'/>";


class UserProfilePage extends React.Component {

  render() {

    return (

      <h1> Hello {username}!</h1>

    );

  }

}

 

ReactDOM.render(<UserProfilePage />, document.querySelector("#app"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="app"></div>

There are still some XSS attacks you need to handle. Some are:

1.XSS attack through dangerouslySetInnerHTML

2.XSS attack through the a.href attribute.

3.XSS attack through attacker controlled props.