DEV Community

visiohex
visiohex

Posted on AI-assisted

Turning any web page into LLM-ready Markdown on Cloudflare Workers

Pasting a web page into an LLM usually means pasting the navbar, the cookie banner, three "related posts" blocks and a footer along with the article. I wanted a single endpoint that takes a public URL and returns only the readable content as Markdown, so I built one into PDF to MD. It runs on Cloudflare Workers, and most of the work turned out to be about deciding when not to trust the first result.

This post walks through the pipeline and the trade-offs. The code samples are simplified from the production version.

1. Refuse the URLs you should never fetch

A "fetch any URL" feature on a server is an SSRF bug waiting to happen, so validation comes first and runs again on every redirect hop:

function assertPublicUrl(url: URL) {
  if (url.protocol !== 'https:') throw badRequest('Use a public HTTPS URL.');
  if (url.username || url.password || (url.port && url.port !== '443')) {
    throw badRequest('Use a standard public HTTPS URL.');
  }
  if (isPrivateHostname(url.hostname)) {
    throw badRequest('Private hosts are not allowed.');
  }
}
Enter fullscreen mode Exit fullscreen mode

isPrivateHostname rejects localhost, raw IPv4/IPv6 literals, .local / .internal names and the RFC 1918 and link-local ranges (169.254.x.x is the cloud metadata classic). Redirects are followed manually (redirect: 'manual', at most three hops) so that a public URL cannot bounce the fetch to https://127.0.0.1/ after the first check passed.

2. Fetch with hard limits

The fetch asks for Markdown first, because a growing number of sites will serve it directly:

Accept: 'text/markdown, text/html;q=0.9, application/xhtml+xml;q=0.8, text/plain;q=0.7'
Enter fullscreen mode Exit fullscreen mode

Everything else is a guardrail:

  • 12-second timeout via AbortSignal.timeout
  • only HTML, XHTML, Markdown and plain text are accepted (a PDF URL gets a clean 415 instead of a garbled conversion)
  • a 5 MB cap enforced twice: once from Content-Length, and again while streaming the body, because Content-Length is optional and can lie

If the response is already text/markdown or text/plain, it is normalised and returned as-is. No conversion is better than any conversion.

3. Find the article, drop the chrome

For HTML, the first pass strips script, style, noscript, svg, iframe, template and head. When "main content only" is on, it looks for <article> and <main>:

function pickBestRegion(article: string | null, main: string | null) {
  if (article && main) {
    // Prefer <article> unless it is clearly a fragment of <main>
    return textLength(article) >= textLength(main) * 0.5 ? article : main;
  }
  return article ?? main;
}
Enter fullscreen mode Exit fullscreen mode

The chosen region only wins if it has at least ~120 characters of real text; otherwise the whole <body> is used. Then nav, header, footer and aside blocks are removed and relative links are made absolute, so the Markdown still works after you paste it somewhere else.

This is deliberately simpler than a full Readability port. It is predictable, cheap on a Worker, and easy to debug when a site does something odd.

4. Convert, then check whether the result is suspiciously thin

The cleaned HTML goes to Workers AI's toMarkdown() when the binding is available, with a hand-written HTML-to-Markdown fallback (headings, lists, links, code blocks, GFM tables) when it is not.

Then comes the check that matters most in practice:

const THIN_CONTENT_THRESHOLD = 80;

if (stripWhitespace(markdown).length < THIN_CONTENT_THRESHOLD && env.BROWSER) {
  const rendered = await tryBrowserMarkdown(finalUrl, env.BROWSER);
  if (rendered && longer(rendered, markdown)) markdown = rendered;
}
Enter fullscreen mode Exit fullscreen mode

A single-page app often returns <div id="root"></div> and a script tag. The direct fetch "succeeds" with almost nothing in it. When the output is that thin, the Worker retries with a headless browser (Cloudflare Browser Rendering, networkidle2, images/media/fonts blocked) and only keeps the rendered result if it is actually longer. Users can also force JS rendering up front.

Browser sessions are the expensive part, so they are rate-limited separately from plain fetches.

5. Return metadata an LLM workflow can use

The response is plain JSON:

{
  "markdown": "---\ntitle: \"...\"\nsource: \"https://...\"\nfetched_at: \"...\"\n---\n\n# ...",
  "title": "...",
  "sourceUrl": "https://...",
  "finalUrl": "https://...",
  "engine": "direct | ai | browser | fallback",
  "wordCount": 1234,
  "charCount": 7890,
  "tokenEstimate": 1973
}
Enter fullscreen mode Exit fullscreen mode

The optional YAML frontmatter keeps the source URL attached to the text, which helps when the Markdown ends up in an Obsidian vault or a RAG index months later. engine tells you which path produced the output, which is the first thing I look at when a page converts badly. tokenEstimate is a rough chars / 4, good enough to decide whether a page fits in a context window.

Trying it

The web version needs no account: URL to Markdown. There is also an API (documented in the OpenAPI schema):

curl -sS -X POST "https://pdf-to-md.app/api/v1/url-to-markdown" \
  -H "Authorization: Bearer $PDFTOMD_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url":"https://example.com/article","mainOnly":true,"includeFrontmatter":true}'
Enter fullscreen mode Exit fullscreen mode

What it does not do

  • Pages behind a login or a paywall are out of scope. It only fetches what an anonymous visitor can see.
  • Heavily interactive pages (dashboards, infinite feeds) convert poorly even with the browser fallback.
  • The <article>/<main> heuristic fails on sites that put everything in nested divs; for those, turning off "main content only" and trimming by hand works better.

If you have a URL that converts badly, I'd genuinely like to see it. Those are the cases that make the heuristics better.

Top comments (0)