A tiny Cloudflare Worker that serves the .md twin of any static page when the request is from a known LLM crawler or explicitly asks for text/markdown. Falls back to the HTML response when the .md twin doesn't exist.
It also ships cloudflare-md-router dev, a local dev loop that serves real builds through wrangler dev, so the Worker's routing works while you edit (see Dev loop).
If you're building a docs site that already emits a per-page raw-markdown twin (e.g. /foo/bar and /foo/bar.md), this lets every page do content negotiation transparently — Claude, ChatGPT, Perplexity, etc. fetch the model-friendly version automatically; humans keep getting the styled HTML page.
| Request | Worker serves |
|---|---|
Anything with a file extension (.css, .png, .md, …) |
Pass-through to ASSETS |
| Non-GET | Pass-through to ASSETS |
Accept: text/markdown |
<path>.md, served as text/markdown; charset=utf-8 (HTML fallback when the twin is not ok) |
User-Agent matches a known LLM bot (unless botUserAgents: false) |
<path>.md, served as text/markdown; charset=utf-8 (HTML fallback when the twin is not ok) |
| Everything else | HTML page — plus a Link header advertising its .md twin |
The twin is fetched without the client's If-None-Match / If-Modified-Since, so a markdown request never gets an asset-worker 304 for it. Once that fetch is ok (2xx), the twin is known to exist and its own ETag is trustworthy, so a markdown client revalidating a twin that exists gets a 304 answered by the worker (weak comparison of If-None-Match, or *, with the twin's ETag; Content-Type: text/markdown; charset=utf-8, no body, Vary: Accept with vary). Otherwise it gets the full twin, or, when the twin is missing, the HTML fallback fetched with the client's original request (which can still revalidate to a 304 of its own). If-Modified-Since alone gives no 304: the asset worker sends no Last-Modified, and RFC 9110 ignores it when If-None-Match is present. The validators are stripped from the twin request because, if they were forwarded, ASSETS could answer it with a 304 that can't be trusted: under not_found_handling: "404-page" a missing twin resolves to the 404 page, so a client holding that page's ETag would get a 304 for a twin that doesn't exist. Treating it as a miss instead would serve the HTML page to a client revalidating its cached markdown.
The HTML fallback needs a missing twin to answer non-ok, so not_found_handling must be "404-page" or "none". With "single-page-application", a missing twin resolves to /index.html with a 200 and is served as markdown, and checkTwin advertises a twin that doesn't exist.
On the normal HTML page response, the worker also adds an RFC 8288 Link header so an agent can discover the markdown twin from a plain GET, without sniffing the User-Agent or guessing the right Accept:
Link: </foo/bar.md>; rel="alternate"; type="text/markdown"This is on by default (only for a 200 text/html reply to an extension-less GET); disable it with advertiseTwin: false.
Because the worker negotiates per request, two clients can get different representations of the same URL. Set vary: true to add a Vary: Accept header to the negotiated responses, so a cache that honors Vary keys on Accept and doesn't serve the HTML page to a client that asked for markdown — or vice-versa. It's off by default: the worker then adds no Vary of its own, and verbatim pass-through responses never get one. Caching says which caches it is for.
The included bot list covers the common ones: GPTBot, ChatGPT-User, OAI-SearchBot, ClaudeBot, Claude-Web, Claude-User, Claude-SearchBot, Amazonbot, DuckAssistBot, anthropic-ai, PerplexityBot, CCBot, Applebot-Extended, Google-Extended, cohere-ai, Bytespider, Diffbot. See src/bots.ts.
Three more opt-in features, all off by default:
checkTwin: truefetches the.mdtwin fromASSETS(the same request a markdown request makes, without the client'sIf-None-Match/If-Modified-Since) before advertising it, so a route with no twin (an error page, say) gets no deadLink. It costs one extra local asset lookup per HTML page.advertiseLlmsTxt: true(or a path) addsLink: </llms.txt>; rel="alternate"; type="text/plain"to HTML pages.canonicalOrigin: "https://example.com"rewrites absoluteog:image/twitter:imageURLs under that origin to the origin being browsed when the request host differs (a preview deploy), viaHTMLRewriter.canonicalandog:urlare left alone.
vary: true matters wherever something stores the Worker's responses:
- A browser, proxy or CDN in front of your site keys on
Acceptwhen it honorsVary. - Workers Caching (
"cache": { "enabled": true }inwrangler.jsonc) stores one variant perAcceptvalue. It answersHEADfrom theGETentry, so aHEADgets the negotiated headers rather than the pass-through. Its key has no hostname, so withcanonicalOrigin(whose image rewrite depends on the host) a page cached on a preview host can be served on the canonical one, or the reverse: keep Workers Caching off for a Worker that serves both. - The zone's cache doesn't hold these responses. The Worker runs in front of it, and it keeps what a Worker fetches from an origin or stores with the Cache API, not what the Worker returns. Zone Cache Rules, and their Vary setting, don't apply. Static assets are cached per file, so a page and its
.mdtwin never share an entry. - Your own Cache API use: put
Acceptin the cache key.
Vary: Accept is the whole story only when Accept is the only routing input. With User-Agent routing on (the default), a bot gets markdown whatever Accept it sends, and a cache stores that reply under the bot's Accept value, so a browser sending the same Accept string can be served it. Pair vary: true with botUserAgents: false (see Accept-only negotiation) if that matters. Vary: User-Agent is intentionally not added, as it would defeat shared caching.
pnpm add @wave-rf/cloudflare-md-routerThis package ships raw TypeScript with no build step — bundle it with Wrangler/esbuild (the Cloudflare Workers default), which resolve the .ts entry points directly.
The simplest setup — re-export the default handler from your worker entrypoint:
// worker/index.ts
export { default } from "@wave-rf/cloudflare-md-router/worker";Configure your wrangler.jsonc with an ASSETS binding pointing at your built static site:
Keep not_found_handling at "404-page" or "none" (the default): the HTML fallback needs a missing twin to answer non-ok, and "single-page-application" answers it with /index.html and a 200 (see Behavior).
run_worker_first: true is the simplest setting: the worker sees every request before Cloudflare's static-asset matcher does. (Without it, the worker only ever runs on 404s.) The catch is that every JS, CSS and image request also invokes the Worker, only for the router to pass it through, and each invocation is billed and adds a little latency.
For a typical static site, scope it to page routes instead. run_worker_first also accepts an array of route patterns (Cloudflare docs):
"assets": {
"directory": "./dist",
"binding": "ASSETS",
"not_found_handling": "404-page",
"html_handling": "drop-trailing-slash",
"run_worker_first": ["/*", "!/_astro/*", "!/assets/*"]
}The Worker runs first when a pattern matches and no ! pattern does; * matches deeply (across /), a ! pattern always wins over a non-negated one, and the order doesn't matter. Everything else is served by the asset matcher without invoking the Worker. At most 100 entries are allowed. Adjust the excluded directories to wherever your build puts hashed assets (/_astro/* for Astro, /assets/* for Vite, and so on). Two things to know:
- A request that matches no pattern never reaches the router, so the array must cover every page route (
"/*"does). - Don't exclude by extension with something like
"!/*.*":*also matches across directories, so it would also exclude any page under a path segment containing a dot (/docs/v1.2/page). The router already passes file-extension requests through verbatim, so excluding asset directories is enough.
Use createMdRouter() if you need to extend the bot list, turn User-Agent routing off, change the .md path mapping, or add other Accept tokens:
// worker/index.ts
import { createMdRouter, LLM_BOT_UA } from "@wave-rf/cloudflare-md-router";
export default createMdRouter({
// Add your own bots:
botUserAgents: new RegExp(LLM_BOT_UA.source + "|mybot", "i"),
// Or serve markdown on an explicit `Accept` only, never by User-Agent (see below).
// botUserAgents: false,
// Treat `Accept: text/x-markdown` as markdown too:
acceptMarkdown: ["text/x-markdown"],
// Custom .md path strategy. Default: `/foo/` → `/foo.md`, `/` → `/index.md`.
mdPathFor: (pathname) => `/markdown${pathname.replace(/\/$/, "")}.md`,
// Don't advertise the `.md` twin via a `Link` header (default: true).
// Left commented out here: it would also make `checkTwin` below a no-op.
// advertiseTwin: false,
// Add `Vary: Accept` to negotiated responses so a cache in front of the
// Worker doesn't cross-serve the HTML and markdown representations
// (default: false).
// With UA routing on (as here), a bot's markdown is cached under that bot's
// `Accept`; use `botUserAgents: false` when the cache must never cross-serve.
vary: true,
// Only advertise a twin that exists (default: false).
checkTwin: true,
// Also advertise /llms.txt via a Link header (default: false).
advertiseLlmsTxt: true,
// Point og:image / twitter:image at the browsed origin on preview hosts.
canonicalOrigin: "https://example.com",
});By default the worker also serves markdown to known crawler User-Agents, which helps crawlers that don't send Accept: text/markdown. Some site owners would rather negotiate on Accept alone, so that no request is answered differently based on who it claims to be (search engines call serving crawlers different content "cloaking"). Pass botUserAgents: false to do that:
// worker/index.ts
import { createMdRouter } from "@wave-rf/cloudflare-md-router";
export default createMdRouter({ botUserAgents: false });Markdown is then served only when the request asks for it: Accept: text/markdown, or one of your acceptMarkdown tokens. Everything else gets the HTML page, still with the Link header advertising the .md twin, so an agent can find it from a plain GET. The trade-off: crawlers that don't negotiate and don't follow the Link header will receive HTML. Because Accept is then the only routing input, vary: true lets a shared cache that honors Vary: Accept store the negotiated responses safely (see Caching).
To run the negotiation as one step of a larger Worker, use createMdResponder(options). It takes the same options and returns a plain (request, env) => Promise<Response>:
import { createMdResponder, type MdRouterEnv } from "@wave-rf/cloudflare-md-router";
const respond = createMdResponder({ vary: true });
export default {
fetch: (request, env) =>
new URL(request.url).pathname.startsWith("/api/")
? Response.json({ ok: true }) // your own routes here
: respond(request, env),
} satisfies ExportedHandler<MdRouterEnv>;astro dev (or any framework dev server) skips everything the Worker adds in production: the .md twins, the Link header, and any outputs that only exist in a real build. If your Worker serves something the dev server can't, use this instead of it. If the Worker adds nothing you are iterating on, keep using the dev server — it has HMR and an error overlay; this does not.
The command runs a full build on every save into a staging directory, copies it into your output directory only if the build succeeded, and serves that directory through wrangler dev --live-reload. A failed build (or the emptied-output window during one) never reaches the browser: you keep the last good build, with a red banner and a terminal bell. Ctrl-C stops the build (its whole process tree) and wrangler, with SIGTERM and then SIGKILL after 5 s, and the command does not exit until they are gone. Each save costs a real build, with errors in the terminal rather than the page.
pnpm add -D @wave-rf/cloudflare-md-router wrangler
pnpm exec cloudflare-md-router dev// package.json
{ "scripts": { "dev:worker": "cloudflare-md-router dev" } }Needs Node 20+ (recursive fs.watch; checked at startup, tested in CI on Node 24 only; POSIX is the supported platform, Windows is best-effort) and a locally-installed wrangler. It is never downloaded: the site's own wrangler package is resolved the way require would (so a workspace-root install works) and its bin is run directly with Node, with no package manager or shell in between to swallow Ctrl-C. If the package can't be resolved (Yarn PnP, or not installed) it falls back to your package manager's local exec (pnpm exec, npm exec --no, yarn, bun x --no-install). That fallback is best-effort on shutdown: on Debian-based images, where /bin/sh is dash, npm and pnpm run it through an sh that does not pass signals on, so the CLI also signals wrangler's descendants directly (the smoke test wrangler run through the <pm> fallback is stopped too covers this under npm and pnpm). Add the staging directory (.dev-<outDir>, so .dev-dist/ by default) to .gitignore.
| Option | Default |
|---|---|
--build <cmd> (MD_ROUTER_DEV_BUILD) |
the site's build script, via the package manager its lockfile indicates (pnpm, yarn, bun or npm; the lockfile is searched up the tree, so monorepos work), else the packageManager field in package.json, else npm. A custom command runs through the shell with node_modules/.bin on PATH, so --build "astro build" works. |
--out-dir <dir> |
assets.directory from wrangler.jsonc / wrangler.json / wrangler.toml (JSONC comments and trailing commas are fine), else dist. A relative path resolves against the wrangler config's directory. The staging directory is .dev-<name> next to it. Both are emptied and refilled on every build, so the command refuses (and says why) an output directory that is: the site root, or any directory outside it (a sibling such as ../shared/dist too); src/, public/, node_modules/ or .git/, inside one of them, or enclosing one; or the wrangler config's directory, or one enclosing it. Neither the output nor the staging directory may hold a package.json or any git-tracked file. The Worker's directory (the directory of wrangler main) depends on where it is: at or above the root or the config's directory, it falls under the rules above (no equal or enclosing output dir); inside assets.directory, where the config itself declares the Worker to be build output (Astro's dist/_worker.js), only an output dir equal to it or inside it is refused; anywhere else it is treated like src/. Directories are compared by identity (device and inode), not by spelling, so SRC on a case-insensitive disk is src even on Linux over a macOS bind mount, and git-tracked files are matched case-insensitively. |
--out-dir-flag <flag> |
--outDir: appended to the build as <flag> <staging> so it writes to staging, not the served directory. Pass "" to disable. Put {outDir} anywhere in --build to place the path yourself (and skip the flag). The staging path (relative to the site root) is also exported as MD_ROUTER_DEV_OUT_DIR. |
--watch <path> |
Added to the defaults: src/, public/, astro.config.*, vite.config.*, tsconfig.json, package.json, .env*. Directories recurse; other entries are root-level file names (a trailing * matches a prefix). A nested file path (config/site.json) can't be watched (watch its directory) and a directory that doesn't exist is skipped; either one, when you passed it, is reported at startup. Repeatable or comma-separated. --no-default-watch drops the defaults. The Worker directory is deliberately not watched — wrangler reloads the Worker itself. Changes never trigger a build when they are under the output or staging directory, node_modules/, .git/, .wrangler/ or a common framework cache (.astro/, .svelte-kit/, .next/, .nuxt/, .output/, .cache/, .turbo/, .vercel/, .parcel-cache/). In a git work tree, a path below a watched directory that git ignores is dropped too — except under a watched directory that is itself gitignored. Root-level files matching an exact name (tsconfig.json, package.json), .env*, or a name you pass are never git-filtered; the prefix-glob defaults (astro.config.*, vite.config.*) are, and Vite's temporary *.timestamp-<ms>[-<hex>].[cm]?js config files (Vite 3-5) are always skipped, anywhere under a watched path. That makes --watch . usable, as long as everything your build writes outside the output directory is in that list or gitignored. Otherwise each build triggers the next. |
--port <n> (PORT) |
4321. If it is taken, the next free port (up to 19 higher, both IPv4 and IPv6 loopback checked) is used and printed — wrangler itself would just die on a busy explicit port. |
--config <file> |
wrangler.jsonc, wrangler.json, then wrangler.toml in the root. A --config that doesn't exist is an error. |
--root <dir> |
the current directory. |
--strict (MD_ROUTER_DEV_STRICT=1) |
off. See below. |
-- <args> |
everything after -- is passed to wrangler dev. |
--help, -h |
prints the options and exits. |
Flags win over env. A failed build, and a build that exits 0 but writes nothing, are both handled: the previous good build stays up. A build that ignores the staging directory and writes straight into the output directory (say astro build && node postbuild.mjs without {outDir}) is called out as such: what is served is whatever it left there, with no last-good-build protection, until you point it at {outDir} or set --out-dir-flag. On a cold start with no output directory yet, the first build must succeed or the command exits 1. When wrangler exits, so does the command, with wrangler's exit code (1 if wrangler was killed by a signal); a Ctrl-C you send exits 0.
Every build in the loop runs with MD_ROUTER_DEV=1 (unless --strict). Use it in your site config to turn off checks that are right for CI but wrong mid-edit — typically a link validator, since a page you are still writing links to pages that don't exist yet. The rendered output should be identical; only the gate differs:
// astro.config.mjs
const watchBuild = Boolean(process.env.MD_ROUTER_DEV);
export default defineConfig({
integrations: [
// Fails the build on a broken link: keep it for CI and `astro build`, skip it in the dev loop.
...(watchBuild ? [] : [starlightLinksValidator({ errorOnRelativeLinks: true })]),
],
});Run cloudflare-md-router dev --strict (or MD_ROUTER_DEV_STRICT=1) to leave the variable unset and get the CI behaviour in the loop.
Most LLMs do better with raw markdown than with rendered HTML — less DOM noise, no Starlight nav chrome, no script tags. Serving the same content at one URL with two representations means:
- One canonical URL per page (good for citations and link-sharing).
- Crawlers and human readers stay aligned automatically.
- Your
llms.txtcan advertise<page>.mdfor explicit fetches; the worker covers the case where the LLM hits the HTML URL anyway.
MIT — see LICENSE.
{ "name": "my-docs", "main": "worker/index.ts", "compatibility_date": "2025-01-01", "assets": { "directory": "./dist", "binding": "ASSETS", "not_found_handling": "404-page", "html_handling": "drop-trailing-slash", "run_worker_first": true } }