Every page on this site is server-rendered. That's how EmDash works: content lives in D1, and a page reads it at request time, so a publish shows up on the next request with no rebuild.
The catch is that every visit runs the Worker and hits the database. For a blog that changes a few times a week, that's a lot of renders producing the same HTML.
So the site sits behind the Workers Cache, and EmDash purges the right pages when I publish. Here's how that's wired up on this site: the route rules, the cache tags, the two places I had to add tags by hand, and the handful of responses that must stay out of the cache.
Turn on the cache provider
Astro has route caching built in. On Cloudflare, you register cacheCloudflare() as the provider in astro.config.mjs:
import { cacheCloudflare } from "@astrojs/cloudflare/cache";
export default defineConfig({
output: "server",
adapter: cloudflare(),
cache: {
provider: cacheCloudflare(),
},
});
That's the whole switch. The adapter sees the provider and turns on Workers Cache in the generated Wrangler config at build time, so there's nothing to add to wrangler.jsonc.
A cache hit never runs the Worker at all. The cache sits in front of it.
Route rules decide how long
Next you tell Astro which routes can be cached, and for how long. Mine look like this:
routeRules: {
"/": { maxAge: 300, swr: 86400 },
"/blog/[...path]": { maxAge: 300, swr: 86400 },
"/guides/[...path]": { maxAge: 300, swr: 86400 },
"/recipes/[...path]": { maxAge: 300, swr: 86400 },
"/r/[...path]": { maxAge: 300, swr: 86400 },
"/search": { maxAge: 60 },
"/rss.xml": { maxAge: 900, swr: 3600 },
"/llms.txt": { maxAge: 3600, swr: 86400 },
},
maxAge is how long a cached page is fresh. swr (stale-while-revalidate) lets the cache keep serving the old copy for up to a day while it re-renders in the background, so visitors almost never wait on a render.
Five minutes looks short for a blog. It's short on purpose, and the reason is purging.
Two notes on the patterns:
/blog/[...path] also matches /blog itself, so one rule covers the index, every post, the tag pages and the per-post llm.txt.- There's no rule for
/[slug]. A rest or param route at the root also matches EmDash's own routes under /_emdash, and caching the admin is a bad day. CMS pages set their lifetime inside the page instead (more on that below).
Cache tags decide what gets purged
The real work happens in the cache tags. EmDash's query helpers return a cacheHint with tags for whatever you just read, and EmDash purges those same tags whenever that content is written.
On a post page that's two lines:
---
import { getEmDashEntry } from "emdash";
const { entry: post, cacheHint } = await getEmDashEntry("posts", slug);
if (!post) return notFound(Astro);
if (Astro.cache?.enabled) Astro.cache.set(cacheHint);
---
Astro.cache.set() merges with the route rule and tags pile up across calls. The hint has tags but no maxAge, so the route rule still decides the lifetime.
List pages do the same with getEmDashCollection(). The home page reads 4 collections, so it sets 4 hints:
const [featured, recent, guides, bookmarks] = await Promise.all([
getEmDashCollection("posts", { ...newest, where: { featured: "1" }, limit: 3 }),
getEmDashCollection("posts", { ...newest, limit: 6 }),
getEmDashCollection("guides", { ...newest, limit: 6 }),
getEmDashCollection("bookmarks", { ...newest, limit: 6 }),
]);
if (Astro.cache?.enabled) {
for (const result of [featured, recent, guides, bookmarks]) Astro.cache.set(result.cacheHint);
}
Publish a guide and the home page drops out of the cache, because it carries the guides tag. Publish a recipe and it stays put.
The tags EmDash can't see
This is where it got less automatic.
Taxonomy terms
Post cards show tag chips. Those labels come from taxonomy terms, and terms that are hydrated onto entries don't bring a cache hint with them. Rename a tag and every page showing the old name stays stale.
So any page that renders term labels reads the terms through a small helper that adds the taxonomy's tag:
import { getTaxonomyTermsWithCacheHint, type TaxonomyTerm } from "emdash";
export async function taxonomyTerms(Astro: AstroGlobal, taxonomy: string): Promise<TaxonomyTerm[]> {
const { data, cacheHint } = await getTaxonomyTermsWithCacheHint(taxonomy, { includeCounts: false });
if (Astro.cache?.enabled) Astro.cache.set(cacheHint);
return data;
}
The layout chrome
Every page renders the site title, the nav and two footer menus from the base layout. Edit a menu and every cached page is wrong.
The obvious fix is calling Astro.cache.set() in the layout. That's too late: cache headers are applied when the page's frontmatter returns, before the layout renders.
So the tags go on in middleware, before the page runs:
const CHROME_MENUS = ["primary", "footer1", "footer2"];
export async function chromeCacheTags(cache: AstroGlobal["cache"]): Promise<void> {
const hints = await Promise.all([
getSiteSettingsWithCacheHint(),
...CHROME_MENUS.map((name) => getMenuWithCacheHint(name)),
]);
for (const { cacheHint } of hints) cache.set(cacheHint);
}
export const onRequest = defineMiddleware(async (context, next) => {
if (context.cache?.enabled && context.cache.options.maxAge !== undefined) {
await chromeCacheTags(context.cache);
}
return next();
});
The maxAge !== undefined check matters. Only routes a route rule already caches get the tags.
The EmDash docs spell out why: a response with any cache hint is cacheable, even with no rule. A tags-only hint makes cacheCloudflare() mark it public with no lifetime, and the Workers Cache falls back to its default of 2 hours for a 200. Tag everything blindly and you've cached routes you never meant to.
CMS pages have no route rule (the /_emdash problem above), so src/pages/[slug].astro sets its own lifetime and adds the chrome tags itself:
if (Astro.cache?.enabled) {
Astro.cache.set({ maxAge: 300, swr: 86400 });
Astro.cache.set(cacheHint);
await chromeCacheTags(Astro.cache);
}
What stays out of the cache
Missing entries
A post URL that doesn't exist yet redirects to /404. Under the /blog rule, that redirect would get cached for 5 minutes.
The bad case is a scheduled post. Someone hits the URL a minute before it goes live, the redirect gets cached, and the post keeps redirecting after it's published. So the miss opts out:
export function notFound(Astro: AstroGlobal): Response {
if (Astro.cache?.enabled) Astro.cache.set(false);
return Astro.redirect("/404");
}
EmDash 1.6 offers another way. getEmDashEntry() now returns the collection tag in its hint when nothing is found. So if you set the hint before rewriting to /404, the miss can be cached for up to 60 seconds and publishing the entry purges it. I've kept the uncached redirect for now. Scanners asking for random slugs would each get their own cache entry, and I'd rather they hit the origin.
Markdown for agents
Posts and pages also answer Accept: text/markdown with a Markdown version. One URL, two bodies, so the cache needs to keep them apart:
Astro.response.headers.set("Vary", "Accept");
if (prefersMarkdown(Astro.request)) return markdownResponse(postMarkdown(post, origin));
Order matters. The Markdown branch returns only after every Astro.cache.set(). A purge clears every variant of a URL together, so both variants need the same tags.
Why 5 minutes
EmDash purges on every write, so in theory maxAge could be a week. Two things keep mine short.
First, scheduled publishing. EmDash publishes scheduled entries from the Cron Trigger and calls the cache provider with their tags. The route caching docs note that Workers Cache purges from cron have been reported to leave pages unchanged even when the API says success: true. A short maxAge puts a ceiling on that: a scheduled post shows up on the index within 5 minutes no matter what the purge did.
Second, purges can fail. maxAge is the backstop.
With swr at a day, the short lifetime costs very little. Visitors get the cached copy while it refreshes.
Checking it
astro dev never caches, so test against a deployed build. cf-cache-status tells you what happened:
curl -sI https://example.com/blog/some-post | grep -i -E "cf-cache-status|age|vary"
HIT is a cached copy. MISS and EXPIRED rendered in the Worker. UPDATING is swr doing its job: you got the stale copy and a re-render started behind it.
The Cache-Tag header doesn't show up in that output. The Workers Cache reads it and strips it, so you can't see your tags from outside. To check them, log the hint in the page.
Two things I learned the slow way
The cache key includes the Worker version, so every deploy starts empty. The Workers Cache docs have a cross_version_cache option if that bothers you. Template changes then only show once entries expire or get purged.
And the cache is per data center. I wrote a script to warm every sitemap page after a deploy, and it worked: the second pass came back mostly HIT. Then the same pages were MISS from Vancouver until someone asked for them there. The warm only filled the data center the build runner happened to hit, so I took it out of the deploy.
Images get this for free in 1.6
EmDash 1.6 caches its own media for a year on sites with a compatible provider like cacheCloudflare(). Originals from /_emdash/api/media/file/ and resized variants from /_image share a tag per stored file, and replacing or deleting an image purges it.
I didn't write anything for that one. I upgraded and it started working.