DEV Community

Cover image for Dompurify : Prevent XSS Attack remove all the script tag.
Anupam Pandey
Anupam Pandey

Posted on

Dompurify : Prevent XSS Attack remove all the script tag.

Problem

Recently i had to build a feature where i take html content from user and save it in to mongodb and after i had to render that html content in browser.
But the problem is that what if user add script file like

alert("hacked")
Enter fullscreen mode Exit fullscreen mode

into the html content then page got stuck.

Solution

To solve this problem i use a package dompurify
DOMpurify is used to prevent the XSS Attack. It remove all the dangerous tag from html and prevent XSS attack.

To prevent we use sanitize method of the DOMpurify

import DOMPurify from 'dompurify';

const clean = DOMPurify.sanitize('<math><mi//xlink:href="data:x,<script>alert(4)</script>">') // becomes <math><mi></mi></math>
Enter fullscreen mode Exit fullscreen mode

If you ask me i always use DOMpurify to clean the html content specially if you get it from api.

So Thanks for reading....

Top comments (0)