/ blog/preventing-xss-in-markdown
blog / preventing-xss-in-markdown / overview.md

Preventing XSS When Rendering Markdown

Markdown allows inline HTML. If you render user-generated markdown without sanitization, you will be hacked.

Markdown parsers (like marked or remark) usually output HTML strings.

If a user writes:

[Click me](javascript:alert('XSS'))
<script>stealTokens()</script>

And you render it blindly, the browser executes the script.

The Fix: You must run the HTML output through a sanitizer like DOMPurify before rendering it.

import DOMPurify from 'dompurify';
import { marked } from 'marked';

const rawHtml = marked(userInput);
const cleanHtml = DOMPurify.sanitize(rawHtml);
// Now safe to inject

Never trust markdown from a database unless you personally wrote it.

Tags

securityreact
0
0