Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it safe to use dangerouslySetInnerHTML with hard coded html strings?

We have an alert component that renders important information for the user. However, this component has somewhat an abstraction where you just need to pass the content as an array of string.

const Component = () => {
    const alertContent = ['This is the first things', 'Second thing', 'third thing'];
    return (
        <AlertComponent content={alertContent} />
    )
}

This successfully displays the content as a list. However, we need to bolden parts of the text for emphasis. I thought about changing the strings in the array to include html tags, then use dangerouslySetInnerHTML to render them. Something like:

const alertContent = ['This is an <b>important</b> text', ...];
return (
    <>
        {alertContent.map(content => <span dangerouslySetInnerHTML={{__html: content}} />)}
    </>
)

I’ve read about cross-site scripting attacks, but most articles I’ve read talk about user inputs and third party APIs. Does hard-coding the html prevent this? Or do I still need to use sanitizers?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you, the coder, create all of the the HTML to be inserted, and are sure that it doesn’t have any XSS vulnerabilities, then yes, it’ll be safe.

dangerouslySetInnerHTML is named as such to tell you primarily that, if used incorrectly, it’s very easy to open your app up to security problems. But if the HTML that gets set is hard-coded and safe, then dangerouslySetInnerHTML is safe too.

Sanitizers are necessary when the markup comes from user input, or from an external service. They’re not needed if the markup comes entirely from your own code.

That said, in this particular situation:

However, we need to bolden parts of the text for emphasis

Why not just use JSX instead?

const alertContent = [<>This is an <b>important</b> text</>, ...];

Writing in JSX when possible is much preferable to having to resort to dangerouslySetInnerHTML.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading