Created
August 11, 2022 13:59
-
-
Save timbryandev/be333579506ff53d552aa13781d9dbb7 to your computer and use it in GitHub Desktop.
Prevent XSS in React via dangerouslySetInnerHTML
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Exampmes: | |
// 1 | |
const markup = `<p>Hola <img src='none.png' onerror='alert("Rainbow mode FTW!")'> Sharon</p>` | |
<DangerousHtml innerHTML={markup} /> // <p>Hola <img src='none.png'> Sharon</p> | |
// 2 | |
<DangerousHtml | |
content={`<p> | |
Hi | |
<script src="https://example.com/malicious-tracking"></script> | |
Fiona, here is the link to enter your bank details: | |
<iframe src="https://example.com/defo-not-the-actual-bank"></iframe> | |
</p>`} | |
/> | |
// Notes | |
* Remember to include or install https://github.com/cure53/DOMPurify | |
*/ | |
import React from 'react' | |
import DOMPurify from 'dompurify' | |
const sanitize = dirty => DOMPurify.sanitize(dirty) | |
const DangerousHtml = ({ innerHTML, tag }) => { | |
const clean = sanitize(innerHTML) | |
if (typeof Tag === 'undefined') { | |
return <div dangerouslySetInnerHTML={{ __html: clean }} /> | |
} | |
return <tag dangerouslySetInnerHTML={{ __html: clean }} /> | |
} | |
export default DangerousHtml | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment