TexToolsAI

Prevent XSS in Streaming LLM Output in Next.js

By VeloForge Labs · · 8 min read

Quick answer: Do not patch the partial Markdown string. On each streamed chunk, re-render the full text so far, convert it to HTML, then sanitize the result. Incomplete tags or links are then cleaned every time. Memoize finished blocks in React so long answers stay fast. Render links as plain text while streaming.

TL;DR: A streaming answer is half-finished Markdown most of the time. If you sanitize the whole text again on every update, partial <img tags and broken links do not reach the page as live elements. One thing still needs care: partial image syntax can turn into a clickable link while it streams. We saw it in a test and fix it below.

Why is streaming different?

When an answer arrives all at once, you convert and sanitize one finished string. When it streams, you get a new fragment every few milliseconds. The tempting code appends each fragment to the page as it arrives:

// Unsafe: do not do this
setHtml((prev) => prev + chunk);
// ...
<div dangerouslySetInnerHTML={{ __html: html }} />

Two things go wrong. First, the chunk is raw model output, so an attacker who can steer the model can put a script-bearing tag in it. Second, even a safe sanitizer cannot judge a fragment properly, because a tag may be cut in half and finished in the next chunk. Model output is untrusted input, the same as a user comment. The OWASP Top 10 for LLM Applications calls trusting it without checks improper output handling. Our earlier guide, Render LLM Markdown output safely, covers images, links and CSP for finished answers. This article is about the streaming part.

The pattern: re-render the whole text

Keep the accumulated Markdown in a variable. Each time you update the screen, run the full pipeline on all of it and replace the output. Never patch the HTML.

// lib/render-markdown.ts
import { marked } from "marked";
import sanitizeHtml from "sanitize-html";

const ALLOWED_IMG_HOSTS = new Set(["cdn.example.com"]);

export async function renderMarkdown(text: string, { streaming = false } = {}) {
  const raw = await marked.parse(text, { gfm: true });
  return sanitizeHtml(raw, {
    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) => {
        if (streaming) return { tagName: "span", attribs: {} }; // plain text until the stream ends
        return {
          tagName,
          attribs: { ...attribs, rel: "noopener noreferrer nofollow ugc", target: "_blank" },
        };
      },
    },
  });
}

This is the same allow-list idea as the finished-answer guide: only https and mailto, images only from hosts you control, safe attributes on links. The extra part is the streaming flag, explained next.

What we found when we tested partial input

We took one test string with an attacker image, a raw <img onerror> tag, a javascript: link, a normal link and an unfinished code fence. We ran renderMarkdown on every prefix of it, one character longer each time. That is 152 inputs, which is what a stream looks like to your renderer. This is one test string, not proof that no other input can fail.

Mode Prefixes with an image from a non-allowed host, a non-https href or an event handler Prefixes with a clickable link to the attacker URL
streaming: false 0 22
streaming: true 0 0

The sanitizer did its job on every prefix: no remote image from an unknown host, no javascript: link, no onerror. A cut-off <img src=x onerror=alert(1) appeared as harmless text, not as an element.

The 22 links are the catch. While the attacker's ![x](https://attacker.example/...) was still being typed, the closing parenthesis had not arrived yet. marked did not see an image. It saw plain text with a bare URL, and with GitHub Flavored Markdown on, a bare URL becomes a link. So for a moment the reader saw a clickable link to the attacker's address. Once the text was complete, the image was removed and the link was gone. A link is not an image request, so the page does not fetch that URL by itself, but a reader could click it.

Setting streaming: true turns every link into plain text. In our run, none of the 152 prefixes had a link. When the stream ends, render once more with streaming: false so real links come back with their safe rel and target.

Call it from a Server Function

You can run marked and sanitize-html in the browser if you wish, but keeping the allow-list on the server means there is one copy of the rules. The Next.js docs say a Server Function can be invoked from a Client Component when you import it from a file with the "use server" directive.

// app/chat/actions.ts
"use server";

import { renderMarkdown } from "@/lib/render-markdown";

const MAX_CHARS = 50_000;

export async function renderChunk(text: string, streaming: boolean) {
  if (typeof text !== "string" || text.length > MAX_CHARS) {
    throw new Error("Invalid input");
  }
  return renderMarkdown(text, { streaming });
}

The Next.js docs also warn that Server Functions are reachable by direct POST requests, not just from your UI. That is why the function checks the type and length of its input. Add your own authentication check here as well if only signed-in users should call it, and add rate limiting; see How to handle API errors and rate limits for the idea.

The Client Component

This component reads a streamed response from your own chat endpoint, keeps the text in a ref, and asks the server to render it at most about six times a second.

// app/chat/answer.tsx
"use client";

import { useRef, useState } from "react";
import { renderChunk } from "./actions";

export function Answer({ endpoint }: { endpoint: string }) {
  const [html, setHtml] = useState("");
  const textRef = useRef("");
  const latest = useRef(0);

  async function show(streaming: boolean) {
    const id = ++latest.current;
    const result = await renderChunk(textRef.current, streaming);
    if (id === latest.current) setHtml(result); // ignore out-of-date results
  }

  async function ask(prompt: string) {
    textRef.current = "";
    const res = await fetch(endpoint, { method: "POST", body: prompt });
    if (!res.body) return;
    const reader = res.body.getReader();
    const decoder = new TextDecoder();
    let timer: ReturnType<typeof setTimeout> | null = null;

    while (true) {
      const { value, done } = await reader.read();
      if (done) break;
      textRef.current += decoder.decode(value, { stream: true });
      if (!timer) {
        timer = setTimeout(() => {
          timer = null;
          void show(true);
        }, 150);
      }
    }
    if (timer) clearTimeout(timer);
    await show(false); // final render: links come back
  }

  return (
    <>
      <button onClick={() => ask("Hello")}>Ask</button>
      {/* html only ever comes from renderMarkdown on the server */}
      <div dangerouslySetInnerHTML={{ __html: html }} />
    </>
  );
}

A few details that matter:

  • textRef holds the raw Markdown. The page only ever shows output from renderChunk.
  • The Next.js docs say Server Actions are dispatched one at a time per client. Calls queue up, so the throttle keeps the queue short, and the latest counter drops any result that is already out of date.
  • The final show(false) call runs after the stream ends, so links are only live in finished text.
  • We type-checked the server function and component against this project's setup. We did not run the component against a live model stream.

Add a Content-Security-Policy

Sanitizing is the main control. A Content-Security-Policy is the backup if a rule ever has a gap. Its img-src directive limits where images may load from, so an injected image to an unknown host is blocked by the browser. Start in report-only mode to see what would break.

Remove hidden characters first

Text that streams in can carry invisible characters too. They do not run code, but they can break string checks and carry hidden instructions. Run the cleaning function from Strip zero-width and hidden Unicode from LLM output on the text before renderMarkdown.

If you would rather not run the pipeline yourself

The same convert-and-sanitize step is available as one request to the TexToolsAI API. You can try it in the playground on the home page without a key. The request format is in the API docs, and a Pro key is described on the pricing page. For a stream you still decide how often to call it, and you should keep it on the server, so check your rate limits first.

Checklist

  • Never append model output to the page as HTML.
  • Keep the whole Markdown text and re-run convert and sanitize on all of it.
  • Throttle updates to a few per second and drop out-of-date results.
  • Render links as plain text while streaming, then render once more at the end.
  • Allow only https and mailto, and images only from hosts you control.
  • Validate input size inside every Server Function, because it can be called directly.
  • Add a Content-Security-Policy with a tight img-src.
  • Clean hidden Unicode characters before conversion.

Frequently asked questions

Can streaming Markdown cause XSS?

Yes, if you put raw chunks into the page as HTML. A tag can arrive in pieces, and the model's text is untrusted. Re-running a sanitizer on the full accumulated text avoids half-finished tags reaching the page as live elements.

Why render links as plain text while streaming?

In our test, unfinished image syntax with a bare URL turned into a clickable link for a moment, because GitHub Flavored Markdown links bare URLs. Plain text during the stream, then a final render with links, avoids that.

Is it fine to sanitize only the final answer?

Not if you show text while it streams. The partial text is on screen, so it needs the same pipeline as the final text. Run it on every update, not only at the end.

Should I sanitize on the client or the server?

Either can work if the allow-list is strict. Using a Server Function keeps one copy of the rules on the server. Because Server Functions can be called directly, validate input size and add authentication there.

Do I still need a Content-Security-Policy?

It is a good second layer. The sanitizer is the main defense, and a tight img-src and script-src limit the damage if a rule ever has a gap.