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
Related Blogs
Migrating from TanStack Start to Next.js App Router: An Architecture Post-Mortem
A deep dive into why we moved our entire CMS away from Vite SSR and TanStack Router, the performance implications of Server Components, and the hydration traps we had to fix.
Beyond JWTs: Designing a Stateful, High-Performance Session Architecture
Stateless JWTs are great until you need to instantly revoke a compromised session. Here's how to build a stateful, Redis-backed authentication system that handles 50k+ concurrent users with sub-millisecond validation.
Fixing Hydration Errors in Next.js: A Structural Approach
Hydration errors are the bane of Next.js developers. Stop fighting the warnings and learn the structural causes behind 'Text content did not match server-rendered HTML'.