AI & Automation

Rendering LLM Output in a Web App - Keep Text as Data Until HTML Is Intentional

Rendering LLM Output in a Web App - Keep Text as Data Until HTML Is Intentional

An LLM response arrives at a web application as a string. That sounds harmless: it is only text. Yet the same string can become visible prose, HTML elements, a link, or executable browser behavior depending on where the application puts it. The model does not make that decision. The rendering pipeline does.

This creates a practical question for a small PHP or JavaScript application: how can it preserve useful formatting without silently treating model-controlled output as trusted markup? The safest answer is not to search for one universal “AI sanitizer.” It is to decide what the destination is allowed to interpret, then use the narrowest rendering path that satisfies that decision.

Model quality and output handling are different problems

A careful prompt may reduce unwanted output, but it does not establish a browser security boundary. A user can influence a prompt directly, retrieved documents can influence it indirectly, and a model can produce surprising syntax without malicious intent. The OWASP GenAI Security Project calls insufficient validation, sanitization, and handling before downstream use improper output handling.

That category is broader than this article: model output can also reach shells, SQL queries, file paths, or tools. Here the scope is deliberately smaller. The downstream component is an HTML page. The question is whether a response should remain text or be interpreted as markup.

It helps to separate two reviews:

  • Content review: Is the answer accurate, appropriate, and suitable to show?
  • Rendering review: Can the browser interpret any part of the answer as code or privileged markup?

A factual answer can still be rendered unsafely. A false answer can be rendered safely as text. Both reviews matter, but they solve different problems.

The sink decides what the string means

Consider a response containing this literal text:

<img src=x onerror=alert(1)>

Inside a plain text node, the angle brackets remain visible characters. Assigned to innerHTML, the browser parses them as markup. MDN therefore describes innerHTML as an injection sink, while the HTML Living Standard specifies it among APIs that parse and insert markup.

This is why “the model returned Markdown” or “the API returned JSON” is not enough to establish safety. A JSON string can later be passed to innerHTML. Markdown can be converted to HTML. Stored output can move through several services before reaching a browser. Trust has to be evaluated at the final sink, not inferred from the transport format.

Default to plain text

If a feature only needs readable prose, plain text is the smallest useful contract. On the server, encode the value for the HTML text context. In PHP, a minimal template can use:

<?php
$modelOutput = (string) $response['text'];
?>
<div class="assistant-response">
  <?= htmlspecialchars($modelOutput, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') ?>
</div>

This converts characters that carry meaning in HTML source into entities before the template reaches the browser. The flags also encode both quote types and replace invalid code-unit sequences instead of silently dropping them. This example is specifically for text between ordinary HTML tags. It is not a universal encoder for JavaScript, CSS, URLs, or every attribute context. The OWASP XSS Prevention Cheat Sheet emphasizes that output encoding depends on the parser context.

When JavaScript receives the response at runtime, use an API that creates text rather than markup:

const output = document.querySelector('.assistant-response');
output.textContent = modelOutput;

Setting textContent replaces the element's children with a text node. There is no HTML parsing step. Use it on an ordinary content element, not a script or style element where text has different semantics.

The trade-off is visible: headings, emphasis, lists, and links appear as literal syntax. That is often acceptable for logs, previews, compact assistants, and administrative screens. Rich rendering should be an explicit product requirement, not an accidental consequence of choosing innerHTML.

Markdown is a format, not a security boundary

Markdown is attractive because it offers useful structure without asking a model to write a complete HTML document. But “render as Markdown” still means “parse text and usually produce HTML.” In addition, the CommonMark specification includes both raw HTML blocks and raw inline HTML. Libraries and configurations differ, so the word Markdown alone says nothing about whether raw HTML is accepted.

A defensible rich-text pipeline has distinct stages:

  1. Receive and retain the original model output as untrusted text.
  2. Parse only the Markdown features the interface needs.
  3. Disable raw HTML in the parser when that option exists.
  4. Sanitize the generated HTML with a maintained allowlist-based sanitizer.
  5. Insert only the sanitized result into an HTML sink.

Disabling raw HTML is useful, but it does not make every parser extension or link safe. Sanitization remains a separate boundary. For browser-side JavaScript, OWASP points to DOMPurify. For a server-side PHP pipeline that intentionally supports rich untrusted HTML, HTML Purifier is one maintained option. These names are examples, not a promise that their default settings match every application's policy.

The policy should be narrower than “all HTML that does not execute script.” A simple assistant may only need paragraphs, lists, emphasis, code, and links. Images can trigger external requests. Forms and embedded frames change the interaction model. Styling can obscure warnings or imitate surrounding controls. Decide which semantics the feature needs, then allow those semantics rather than trying to enumerate every dangerous string.

Links need their own decision

An escaped string can still become a risky destination if the application later places it in href or src. HTML attribute encoding protects the surrounding markup syntax; it does not decide whether a URL scheme or destination is acceptable.

A renderer should define a link policy separately. For example, it might permit only https: links, resolve relative links against a known base, or remove links entirely in an internal assistant. If external links open a new tab, the application should also apply its normal relationship and referrer policy. There is no single correct allowlist for every product, but leaving the choice to whatever text the model emits is not a policy.

The same principle applies to other contexts. A model-proposed class name, CSS value, JSON field, filename, or command argument should be checked according to the grammar and authority of its destination. HTML sanitization does not make those other uses safe.

Sanitization is a maintained boundary

Sanitization is not a one-time regular expression. Browsers parse malformed markup, nested namespaces, attributes, and URLs according to detailed rules. A maintained sanitizer uses a parser and an explicit policy to remove or transform constructs it does not allow.

That boundary can still be weakened. The DOMPurify documentation warns that changing sanitized markup afterward can void the protection. A plugin may also reinterpret attributes, or a later template step may concatenate new unsanitized strings. The safest flow is short: parse, sanitize, and insert, without another markup-producing transformation in between.

Dependencies also need updates. Sanitizers operate against browser behavior, and bypasses can be discovered. Pinning a reviewed version is useful for reproducible deployments, but it needs an update process rather than permanent neglect.

CSP and Trusted Types are backstops

A restrictive Content Security Policy can reduce the impact of some injection mistakes, but OWASP advises against treating CSP as the primary XSS defense. Correct sinks, context-aware encoding, and sanitization come first.

Trusted Types goes one step further by letting supporting browsers require typed values at covered injection sinks. It can make an accidental assignment of an ordinary string to a sink such as innerHTML fail unless a policy transforms it. That is useful enforcement, but it is not a sanitizer by itself: a permissive policy can bless unsafe HTML. The cited specification is also a W3C Working Draft, so an application should check current browser support and treat it as defense in depth rather than a universal baseline.

A small rendering contract

Before implementing an LLM response panel, write down a compact contract:

  • Is the output plain text, restricted Markdown, or intentionally supported HTML?
  • Which elements, attributes, and URL schemes are actually required?
  • Where does encoding or sanitization occur, and can later code bypass it?
  • Are streaming chunks kept as text until parsing is complete?
  • Are the original text and sanitized rendering distinguishable for debugging without logging secrets unnecessarily?
  • Which tests cover angle brackets, quotes, links, raw HTML, malformed markup, and parser extensions?

Streaming deserves particular care. A sanitizer generally needs a coherent fragment; repeatedly appending partial model chunks through innerHTML creates both parsing ambiguity and a larger sink surface. Accumulating chunks as text and rendering after a complete unit is simpler. If live rich rendering is essential, it needs a parser designed for incremental input and the same final sanitization policy.

Conclusion

An LLM does not need to be malicious for its output to cross a dangerous boundary. The application creates that boundary when it asks a browser to interpret a string. Plain text avoids most of the complexity and should be the default whenever it meets the interface's needs.

When rich formatting is genuinely useful, make each transition visible: text becomes Markdown syntax, the parser produces HTML, the sanitizer applies an allowlist, and only then does the browser receive markup. Links and other destination-specific values still need their own policy. CSP and Trusted Types can catch mistakes, but they do not replace that pipeline. The useful question is therefore not “Can this model generate HTML?” but “What, exactly, does this interface need permission to interpret?”

References