Serving Markdown to AI agents from an EmDash site

Roger StringerRoger Stringer
November 25, 2026
6 min read
Serving Markdown to AI agents from an EmDash site

When I fetch my short-link post as HTML, I get about 104 KB back. Ask the same URL for Markdown and it's about 25 KB, with no nav, no footer, no class soup, and nothing but the article.

That gap matters when the reader is an agent. Every byte of layout markup is a token it has to pay for and then ignore. And some agents already ask for the lean version: Checkly tested which coding agents send Accept: text/markdown and found Claude Code, Cursor and OpenCode do.

So this site answers them. Every post, guide and CMS page on rogerstringer.com returns Markdown when the request prefers it, and there's an llms.txt index plus full-text files for crawlers that want everything at once. It runs on EmDash and Astro on Cloudflare Workers, and the whole thing is two small utility files and a few lines per page.

Here's how it's built, including the caching detail that's easy to get wrong.

What an agent can ask for

There are four ways in:

  • Any post, guide or page URL with Accept: text/markdown gets that page as Markdown. Same URL, different representation.
  • /llms.txt is the index, following the llms.txt format: what the site is, links to the full-text files, and a line for every post, guide and page.
  • /blog/<slug>/llm.txt is a single post as a plain-text entry. The old version of this site had these, so I kept the URLs.
  • /llm-full.txt, /blog/llm-full.txt, /guides/llm-full.txt and /llm-full-pages.txt are everything, or one section, in one file.

All of them come from the same Portable Text to Markdown converter, so a fix there shows up everywhere.

Deciding who wants Markdown

The lazy version is accept.includes("text/markdown"). It works until a client sends something like text/markdown;q=0.1, text/html, which means "Markdown if you must, but I'd rather have HTML."

I ported the negotiation from my old site's middleware and kept it honest to RFC 9110: parse the q values, let the most specific matching range decide each type's weight, and pick the winner.

const PRODUCES = ["text/html", "text/markdown"] as const;

export function prefersMarkdown(request: Request): boolean {
	const header = request.headers.get("accept");
	if (!header) return false; // no Accept header means HTML
	const entries = parseAccept(header);
	let best: string | null = null;
	let bestQ = -1;
	let bestPosition = Number.POSITIVE_INFINITY;
	for (const candidate of PRODUCES) {
		// The most specific matching range sets this type's q,
		// so `text/html;q=0, */*` really does reject HTML.
		let matched: AcceptEntry | null = null;
		let position = Number.POSITIVE_INFINITY;
		entries.forEach((entry, index) => {
			if (!matches(entry, candidate)) return;
			if (!matched || entry.specificity > matched.specificity) {
				matched = entry;
				position = index;
			}
		});
		const q = matched?.q ?? 0;
		if (q <= 0) continue;
		// Highest q wins; ties go to whichever the client listed first.
		if (q > bestQ || (q === bestQ && position < bestPosition)) {
			best = candidate;
			bestQ = q;
			bestPosition = position;
		}
	}
	return best === "text/markdown";
}

parseAccept splits the header into { type, q, specificity } entries, where */* is 0, text/* is 1 and an exact type is 2. A browser sends text/html first with a */* fallback, so it always gets HTML. An agent that puts text/markdown first gets Markdown.

The page: one URL, two variants

In the post template, the Markdown branch is three lines at the very end of the frontmatter:

---
const { entry: post, cacheHint } = await getEmDashEntry("posts", slug);
if (!post) return notFound(Astro);
if (Astro.cache?.enabled) Astro.cache.set(cacheHint);

// ...tags, related posts, each with its own Astro.cache.set()...

Astro.response.headers.set("Vary", "Accept");
if (prefersMarkdown(Astro.request)) {
	return markdownResponse(postMarkdown(post, Astro.site?.origin ?? Astro.url.origin));
}
---

The position matters more than the code.

Pages on this site are edge-cached with Workers Cache, and EmDash purges them by cache tag whenever content changes. Vary: Accept tells the cache to keep one copy per Accept value, so the HTML and Markdown versions of a post live side by side under the same URL. A purge clears every variant of that URL together.

That gives you two rules:

  1. Both variants need Vary: Accept. The HTML response sets it too. Without it, whichever variant got cached first gets served to everyone, and a browser can end up with a wall of Markdown.
  2. The Markdown branch returns after every Astro.cache.set(). If it returned early, the Markdown variant would carry fewer tags than the HTML one. Rename a tag, and the HTML purges while the Markdown keeps the stale name until it expires.

markdownResponse itself is tiny:

export function markdownResponse(markdown: string): Response {
	return new Response(markdown, {
		headers: { "Content-Type": "text/markdown; charset=utf-8", Vary: "Accept" },
	});
}

You can see both variants with curl:

curl -sI -H "Accept: text/markdown" https://example.com/blog/my-post | grep -i -E "content-type|vary"
# content-type: text/markdown; charset=utf-8
# vary: Accept

curl -sI -H "Accept: text/html" https://example.com/blog/my-post | grep -i -E "content-type|vary"
# content-type: text/html
# vary: Accept

Portable Text to Markdown

EmDash stores rich text as Portable Text, and emdash/client ships portableTextToMarkdown. It handles paragraphs, headings, lists, links, code blocks and images well. It doesn't know about some things my content uses:

  • Tables. The converter skips table blocks, and I only noticed when a post with a schema table showed up in llm.txt without it.
  • Section breaks. EmDash 1.6 started escaping a paragraph that's just ---, so faking a horizontal rule as a paragraph now comes out as \---.
  • Custom widget blocks. My code tabs, steps and accordion blocks would come out as JSON comments.
  • Relative image URLs. Fine in a browser, useless in a file an agent reads somewhere else.

So toMarkdown converts the body in runs and handles those blocks itself:

export function toMarkdown(value: unknown, origin: string): string {
	if (!Array.isArray(value)) return "";
	const parts: string[] = [];
	let run: Block[] = [];
	const flush = () => {
		if (run.length) parts.push(portableTextToMarkdown(run).trim());
		run = [];
	};

	for (const block of value as Block[]) {
		if (block._type === "table") {
			flush();
			parts.push(tableToMarkdown(block));
		} else if (block._type === "break") {
			flush();
			parts.push("---");
		} else if (block._type === "block" || block._type === "code") {
			run.push(block);
		} else if (block._type === "image") {
			const url = block.asset?.url;
			run.push(url ? { ...block, asset: { ...block.asset, url: new URL(url, origin).href } } : block);
		} else if (block._type.startsWith("widget.")) {
			run.push(...flattenWidget(block));
		}
		// Anything else (marketing blocks, embeds) is dropped.
	}
	flush();
	return parts.filter(Boolean).join("\n\n");
}

Normal blocks pile up in run and go through EmDash's converter in one call. A table or a break flushes the run and gets written directly. Widgets become plain bold titles, paragraphs and code blocks, which the converter already handles.

The table writer sends each cell through the same converter as a one-off paragraph, so inline code and links inside cells survive:

const cellText = (cell: TableCell) =>
	portableTextToMarkdown([
		{ _type: "block", _key: "cell", style: "normal", markDefs: cell.markDefs ?? [], children: cell.content ?? [] },
	])
		.trim()
		.replace(/\\?\s*\n+\s*/g, " ") // a row has to stay on one line
		.replace(/\|/g, "\\|");

GFM tables need a header row, so a table without one uses its first row. Short rows get padded with empty cells.

The real file also merges consecutive blockquote blocks back into one quote, because the converter puts a blank line between them and that splits a > [!NOTE] callout in half.

llms.txt and the full-text files

The index is an Astro API route that reads posts, guides and pages and writes Markdown:

export const GET: APIRoute = async ({ site, url, cache }) => {
	const origin = site?.origin ?? url.origin;
	const at = (path: string) => new URL(path, origin).href;
	const [posts, guides, pages] = await Promise.all([
		getEmDashCollection("posts", { orderBy: { published_at: "desc" } }),
		getEmDashCollection("guides", { orderBy: { published_at: "desc" } }),
		getEmDashCollection("pages"),
	]);
	if (cache?.enabled) for (const result of [posts, guides, pages]) cache.set(result.cacheHint);

	const line = (title: string, href: string, description?: string | null) =>
		`- [${title}](${href})${description ? `: ${description}` : ""}`;

	const text = `# My Site

Every post, guide and page is also available as Markdown: request its URL with \`Accept: text/markdown\`.

## Posts

${posts.entries.map((p) => line(p.data.title, at(`/blog/${p.id}`), p.data.excerpt)).join("\n")}
`;
	return new Response(text, { headers: { "Content-Type": "text/markdown; charset=utf-8" } });
};

That one sentence near the top is the cheapest part of the whole setup. An agent that lands on llms.txt learns it can ask any URL for Markdown, without guessing at .md suffixes.

The full-text files reuse the per-entry helpers. /blog/llm-full.txt maps every post through postLlm() and joins them, and each route calls cache.set() with its collection's hint, so publishing a post purges the files that include it.

What I'd check on your own site

If you add this to an EmDash site, these are the spots worth testing:

  • Request a page with Accept: text/markdown, then with a normal browser Accept header, and confirm each gets its own content type and both send Vary: Accept.
  • Put the Markdown branch after your last Astro.cache.set(), never before.
  • Run your real posts through the converter and read the output. Tables, custom blocks and anything that looks like Markdown syntax in plain text are where it breaks.
  • Re-check after EmDash upgrades. The 1.6 escaping change was a one-line fix, but only because I read the release notes before deploying.

The agents asking for Markdown today are mostly coding tools reading docs. But it costs a few lines per template, and a 25 KB answer beats a 104 KB one for every agent that bothers to ask.

Do you like my content?

Sponsor Me On Github

Keep reading