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

Time:04-09

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?

CodePudding user response:

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.

CodePudding user response:

If a text to be rendered in dangerouslySetInnerHTML is set by administrators or proved users, it should be safe and no problem.

But if normal users can set the texts or html contents, you should consider it.

You can provide html UI editors such as TinyMCE for users to set html content and implement some logic to strip the dangerous html tags such as iframe, script , etc on your backend apps.

  • Related