Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React documentation - JSX Prevents Injection Attacks [closed]

I am learning REACT JS using their own documentation. And when i came to a section JSX Prevents Injection Attacks, I got confused about this topic. how JSX prevents from injection attacks? Can anyone explain me on this, please.

The said text in documentation about the topic is:

It is safe to embed user input in JSX.

const title = response.potentiallyMaliciousInput;
// This is safe:
const element = <h1>{title}</h1>;

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.

like image 284
Subin Avatar asked Sep 06 '26 05:09

Subin


1 Answers

Because JSX renders text as text, HTML in user input is not treated as HTML, just as plain text. An example is probably the simplest way to show this:

class Example extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            userContent: `So I told the guy <script src="http://example.com/malicious-script.js><\/script>`
        };
    }
    
    render() {
        return <div>User content: {this.state.userContent}</div>;
    }
}

ReactDOM.render(<Example/>, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Notice how the script tag is rendered as text. It doesn't create a script element, it's just characters (<, s, c, r, etc.).

like image 69
T.J. Crowder Avatar answered Sep 07 '26 19:09

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!