Route Caching

On this page

Astro’s route caching stores the rendered response of an on-demand page, so a cache hit skips rendering. EmDash supplies cache tags for the content a page renders and invalidates those tags when the content changes. Pages can stay cached for days while a publish usually becomes visible within seconds.

The object cache stores query results and still renders every page. With a cache provider configured, anonymous renders skip the object cache and read from the database, so a render that refills an invalidated page doesn’t come from an older snapshot (see What gets cached). The route cache then serves anonymous visitors, and the object cache mainly speeds up renders for signed-in editors.

Choose a cache provider

Route caching needs a cache provider. Use the one that matches your deployment:

DeploymentProviderImport from
Node.jsmemoryCache()astro/config
CloudflarecacheCloudflare()@astrojs/cloudflare/cache

memoryCache() keeps entries in the memory of the server process. cacheCloudflare() is a CDN provider: it stores responses in the Cloudflare Workers Cache, and a cache hit never runs the Worker. Astro’s Netlify and Vercel adapters ship CDN providers as well; see Adapter cache providers. EmDash invalidates through Astro’s provider-independent cache.invalidate() API, so its tags work with any provider. Provider differences covers the behavior that depends on the provider. astro dev never caches, so test caching against a production build.

Configure route caching

Register the provider and declare which routes may be cached, for how long, and under which tags. This example uses the Cloudflare provider; on Node, use cache: { provider: memoryCache() } with memoryCache imported from astro/config:

import { defineConfig } from "astro/config";
import { cacheCloudflare } from "@astrojs/cloudflare/cache";

export default defineConfig({
	// ...your existing output, adapter, and integrations
	cache: {
		provider: cacheCloudflare(),
	},
	routeRules: {
		"/": { maxAge: 86_400, swr: 604_800, tags: ["posts", "pages", "all"] },
		"/blog": { maxAge: 86_400, swr: 604_800, tags: ["posts", "all"] },
		"/blog/[slug]": { maxAge: 86_400, swr: 604_800, tags: ["posts", "all"] },
		"/sitemap.xml": { maxAge: 86_400, swr: 604_800, tags: ["posts", "pages", "all"] },
		"/sitemap-[collection].xml": { maxAge: 86_400, swr: 604_800, tags: ["posts", "pages", "all"] },
	},
});
  • maxAge is how long the cache serves the entry before the route renders again. EmDash invalidates stale entries on publish (below), but an invalidation can fail, so maxAge also bounds how long a page can stay stale, plus one stale response while swr revalidates it. Check Provider differences before choosing a long value.
  • swr lets the cache keep serving a stale entry while it revalidates in the background, so visitors rarely wait on a render once a page is cached.
  • tags name the entry for invalidation. Tag each route with the collections it renders, using the collection names: EmDash’s built-in invalidation uses collection names, so matching tags are invalidated automatically. A broad extra tag on every cached route (here all, which is not a collection name, so EmDash never invalidates it on its own) works as an emergency switch: invalidating it, for example with context.cache.invalidate({ tags: ["all"] }) in an endpoint you protect yourself, clears everything at once.

The query helpers also return a cacheHint you can pass to Astro.cache.set() inside the page. Its tags name the exact entry (getEmDashEntry), the collection (getEmDashCollection), or the chrome resource (getMenuWithCacheHint, getSiteSettingsWithCacheHint, getTaxonomyTermsWithCacheHint, getWidgetAreaWithCacheHint). These are the same tags EmDash invalidates on writes, so a page that passes its hints is invalidated when an entry or chrome resource it renders is written, including ones its route rule doesn’t name:

---
import { getEmDashEntry } from "emdash";

const { slug } = Astro.params;
if (!slug) return Astro.rewrite("/404");

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

Astro.cache.set() merges with the route rule, and tags accumulate across calls. The cache hints carry tags but no maxAge, so the route rule decides how long a page is cached.

Give every public route an explicit rule. Rules match the request path, so list your public routes individually: a rest parameter at the site root, such as /[...slug], also matches the admin and API routes under /_emdash/.

Invalidation on publish is built-in

EmDash’s content API routes invalidate the route cache whenever live content changes: publishing, unpublishing, deleting, or restoring an entry from the trash, and saving changes that reach the live entry, invalidate the tags [collection, id]. Creating or duplicating an entry invalidates nothing, because the new entry is a draft. Any route rule tagged with the collection name (as above) is therefore usually refreshed within seconds of a publish, even with a long maxAge.

With revisions, autosaved content-field edits stay in a draft revision and do not purge the route cache. Changes to live metadata, such as bylines, can still trigger a purge. Without revisions (including collections with only drafts), autosaves update the live row and each save purges the collection and entry tags, even for entries that have never been published. Enable revisions when content edits should stay private until publication. For collections that save directly to the live entry, see Purge rate limits before choosing a cache lifetime.

Site chrome is covered too: saving site settings invalidates emdash:settings, menu edits invalidate emdash:menu:{name}, and taxonomy and widget-area writes invalidate their matching emdash:taxonomy:{name} / emdash:widget-area:{name} tags. Pages pick these tags up automatically when they use the cacheHint from getMenuWithCacheHint(), getSiteSettingsWithCacheHint(), getTaxonomyTermsWithCacheHint(), or getWidgetAreaWithCacheHint().

Menu tags cover menu edits only. Publishing, unpublishing, trashing, or restoring an entry that a menu links to, or changing the slug of a linked entry or taxonomy term, doesn’t invalidate the menu’s tag. A page that shows the menu picks up such a change when its tags also name that entry, its collection, or that term’s taxonomy, and otherwise when the page expires.

Creating, editing, or deleting a redirect invalidates the cached page at the redirect’s source path, with and without a trailing slash, so the redirect applies on the next request.

The comment API routes invalidate [collection, id] for the commented entry when a submission is approved immediately, when admin moderation moves a comment into or out of approved status, or when deletion removes an approved comment or reply. Bulk moderation and deletion invalidate only the entries whose approved comments change. Pending submissions, moderation between non-approved statuses, and deletion of non-approved comments without approved replies leave the route cache unchanged. Comment moderation through the plugin API (ctx.comments.moderate) does not invalidate the route cache.

Restoring an older revision, and changes to bylines and the media library, invalidate no pages. Cached pages affected by those changes or plugin comment moderation update once they expire or the entry that renders them is saved again. Media files have their own tag; see Media files. Scheduled publishing attempts tag invalidation on Cloudflare, but cached pages can remain stale; Node does not invalidate them. See Provider differences before relying on scheduled content appearing in cached pages.

This is also why the tag convention matters: EmDash invalidates collection names, entry ids, and the emdash:* chrome tags. If your route rules use other tag names, the built-in invalidation will not match them and stale entries survive until maxAge expires.

Media files

With a compatible cache provider, such as cacheCloudflare(), EmDash caches whole image files served from /_emdash/api/media/file/ for one year, tagged emdash:media:<storageKey>. Resized variants from /_image use the same tag and lifetime only with Astro’s stock sharp service on Node or @astrojs/cloudflare/image-service-workerd on Cloudflare. EmDash does not populate Astro’s memoryCache() with media responses, regardless of their size. A custom cache provider must keep distinct href values and transform options separate in its cache keys and preserve conditional request behavior; configuring a provider alone does not establish that compatibility.

Replacing an image purges that tag, which removes the original and every cached variant at once. Deleting a media item purges it when the stored file was removed: from the admin media library or media picker, the MCP media_delete tool, or ctx.media.delete() in a plugin route. On Cloudflare, stored files that the hourly cleanup removes later, after a delete could not remove them, are purged then. A failed or rate-limited purge leaves the old image cached until the entry expires; purge the tag again to clear it. The same applies to a response that was still being generated while the purge ran: the cache stores it afterwards with the old image.

Some deletes are not purged:

  • Files removed directly from the storage bucket.
  • ctx.media.delete() called from a plugin hook or cron job, except on Cloudflare once a Cron Trigger has run in that Worker isolate.
  • On Cloudflare, a sandboxed ctx.media.delete() that finishes after its plugin route exceeded the wall-time limit, when the route never completes.
  • Stored files removed by the hourly cleanup on Node.
  • Media whose storage key exceeds 1,011 characters or contains characters other than ASCII letters, digits, ., _ and -. EmDash serves these files without automatic route caching. The full emdash:media:<storageKey> tag must fit Cloudflare’s 1,024-character purge limit.

Audio, video, and other non-image files are not cached. A file URL with a query string, including the admin’s _emdash_media preview parameter, is not stored in the cache.

For variants, the href must be exactly /_emdash/api/media/file/<storageKey> or that path prefixed with the request’s origin to be stored. A nested query string (including _emdash_media), a fragment, a foreign origin, or an alternate spelling of that path keeps the variant out of the cache. These source values pass through unchanged to the existing image handling. Both the relative and same-origin absolute forms are accepted, so they can occupy separate cache entries for the same image and transform.

With either stock image service, a /_image URL for EmDash media redirects with a 301 when its outer query has unknown or repeated parameters, lists them in a different order than Astro writes them, or encodes a value differently (for example an href with unencoded /). This normalization applies even without a cache provider and preserves the href value, including any nested query. URLs built by <Image> and getImage() with the stock services are already canonical. Custom image services keep their existing handling without these redirects or automatic variant caching; EmDash does not strip their parameters.

Browsers still revalidate media on every visit, because browser caches can’t be purged.

Middleware that answers these URLs differently depending on a request header, such as serving another image format for some Accept values, must set Vary naming that header on every response for the URL, including the responses it passes through from EmDash. Without it, the cache serves the first response it stored to every visitor. Responses the middleware builds itself need the same emdash:media:<storageKey> tag, so that replacing or deleting the image also purges them.

Keep responses out of the cache

Route rules match the request path, so they also apply to responses you do not want cached under a long TTL. EmDash keeps responses rendered for a signed-in user, and responses sent with Cache-Control: private or no-store, out of the route cache automatically. It limits cacheable 404 responses to a short lifetime, as described below. Other error responses and your own middleware redirects are the template’s job, opted out per request with Astro.cache.set(false).

Astro.cache.set(false) only holds until the next Astro.cache.set() call. A layout renders after the page frontmatter, so a layout that sets a cache hint turns caching back on for a page that opted out. Pass the opt-out to the layout (for example as a prop) and skip its Astro.cache.set() calls when it is set.

EmDash’s middleware opts these responses out of the route cache itself, so no template code is needed: requests carrying a ?_preview= token (valid or not, because those URLs are per-token and a cached draft would otherwise stay reachable after the token expires), and responses with the editor toolbar injected. With toolbar: "client", the same applies to ?_edit URLs. Valid preview responses and toolbar-injected responses are additionally marked Cache-Control: private, no-store for browsers and downstream CDNs.

Error responses

For public page paths handled by the redirect middleware, a 404 with active cache options is cached for at most 60 seconds, with no stale-while-revalidate window. A shorter maxAge, including zero, is preserved. This covers content misses answered with Astro.rewrite("/404"). The options can come from a route rule, the page, or the 404 page and its layout: a tags-only hint available when middleware checks the rendered response is enough, even without a route rule. Hints set later while the body streams may arrive too late; use an explicit route rule for predictable caching and purge tags.

Tag the route with the collection or taxonomy it looks up, even when no entry or term is found. For example, use tags: ["posts"] on /posts/[slug] and tags: ["emdash:taxonomy:category"] on /category/[slug]. Publishing an entry invalidates its collection tag, saving a taxonomy term invalidates its taxonomy tag, and adding a redirect invalidates its source path. Without a matching tag, or if a purge fails, new content can keep returning the cached 404 until its short lifetime expires. Shipped template layouts set settings and menu hints, so their content-miss 404s can become cacheable without a route rule, but those hints alone do not purge the miss when new content is published.

Cache hits skip rendering and writing to the 404 log, so the admin’s 404 hit counts record origin misses rather than every request. Each distinct missing URL occupies its own cache entry; scanners requesting random slugs get no reuse and can evict useful pages from a size-limited cache such as memoryCache(). To keep a miss uncached, call Astro.cache.set(false) in the 404 page’s frontmatter (or in the miss branch for a directly returned 404), and keep later layout code from re-enabling caching.

URLs that match no Astro route still have no route-cache handle and remain uncached. Internal paths (/_emdash, /_image) bypass the redirect middleware and do not get this 404 lifetime limit. Paths ending in a file extension match exact redirect rules only; their 404 responses also skip this lifetime limit.

Other error responses, such as a 500 rendered on a cached route, inherit the rule’s TTL. Opt them out with Astro.cache.set(false).

Redirects in middleware

Middleware that short-circuits with a redirect (for example, host canonicalization) must opt out with context.cache?.set(false). Otherwise the redirect is cached under the route rule’s TTL, and on a CDN provider that doesn’t separate cache entries by hostname it can be served to requests for the canonical hostname too, causing an instant redirect loop. Use optional chaining: context.cache is undefined on some responses, such as the 404 page for a URL that matches no route.

Editors and cached pages

The route cache stores one shared variant per URL, and its cache key ignores cookies, so a cache hit never reflects an editor’s session. With the default server-rendered toolbar, an editor browsing the public site is usually served the cached anonymous variant, without the toolbar, and the emdash-edit-mode cookie has no effect on a cached URL. A page rendered for a signed-in editor is never stored in the shared cache; the next anonymous visitor fills it.

Set toolbar: "client" for sites that use route caching. A small script then shows the edit pill to signed-in editors on cached pages, and the edit view loads from an ?_edit URL that is always rendered fresh. Preview links bypass the cache in either mode.

Provider differences

Node.js with memoryCache()

  • Each server process keeps its own cache, and an invalidation only clears the process that handled the write. If you run several processes or instances, the others keep serving their cached pages until maxAge expires.
  • A restart empties the cache.
  • memoryCache() needs a positive maxAge to store a response. EmDash’s tags-only cache hints do not normally provide one, but a cacheable content-miss 404 is an exception: EmDash supplies a lifetime of up to 60 seconds if it sees active cache options when checking the rendered response, even without a route rule. This includes tags supplied by the 404 page or its layout. To keep these misses uncached, call Astro.cache.set(false) rather than relying on the absence of a rule.
  • Scheduled publishing does not invalidate the route cache on Node. A page that lists a scheduled entry shows it once its cached copy expires, so keep maxAge short on routes that list scheduled content.
  • EmDash does not automatically cache original media files or resized variants with memoryCache(). Its cache-key normalization and conditional request handling do not preserve the media endpoint’s behavior. Use a compatible provider for media caching; page caching remains available with memoryCache().

Cloudflare with cacheCloudflare()

  • The provider writes Cloudflare-CDN-Cache-Control and Cache-Tag response headers. The Workers Cache consumes both; clients never see them, and any Cache-Control header your pages set for browsers is unaffected.
  • When a cache provider is configured, the @astrojs/cloudflare adapter enables the Workers Cache automatically: the build writes "cache": { "enabled": true } into the generated Wrangler configuration that wrangler deploy picks up.
  • A route without a rule is marked no-store, but only if nothing calls Astro.cache.set() while it renders. A cache hint without maxAge, like the ones from getSiteSettingsWithCacheHint() and getMenuWithCacheHint(), produces Cloudflare-CDN-Cache-Control: public without a lifetime, so the Workers Cache falls back to its default cache lifetimes (2 hours for a 200 response). If your layout sets these hints, every page that uses the layout becomes cacheable, with or without a rule.
  • By default the Worker version is part of the cache key, so every deploy starts with an empty cache and the first requests after it render in the Worker. To keep entries across deploys, set "cache": { "enabled": true, "cross_version_cache": true } in your Wrangler configuration (see Cross-version caching). Template changes then only show once the affected entries expire or are invalidated.
  • Scheduled publishing calls the cache provider from the Cron Trigger with the published entries’ tags, but Workers Cache purges from cron have been reported to leave cached pages unchanged even when the Workers Cache API returns { success: true } (this result is not exposed through Astro’s invalidation API). The content publishes on time; cached pages can keep the old content until expiry or an admin write that changes live content invalidates their tags. See the upstream report. If scheduled content needs to appear promptly, keep maxAge short on affected routes and account for the additional stale-serving window allowed by swr, or opt those routes out of caching.

Purge rate limits

The Cloudflare provider invalidates by purging the Workers Cache. Workers Cache purges always use Cloudflare’s Free plan purge limits, whatever plan your account is on: 5 requests per minute with a burst of 25, per account (see Purge rate limits). Most content writes cost one purge request each: saves that change live content (including autosaves in collections that save directly to the live entry), publishing, unpublishing, deleting, restoring, scheduling, and assigning taxonomy terms to an entry, plus every settings, menu, taxonomy, or widget edit. Replacing an image, and deleting one whose stored file was removed, costs one purge request each, so a bulk delete of images in the media library can use up the burst on its own. Deleting other files, such as documents, audio or video, costs none. A redirect write costs one purge request per source path variant, so up to four when a redirect’s source changes.

Each comment approved on submission costs one purge request, even when submitted by a logged-out visitor. Each admin comment status change or deletion that changes the approved comments shown on a page costs one request. A bulk comment action that changes approved comments costs one or two purge requests, depending on how many entries it touches. Actions that leave approved comments unchanged cost none.

A rate-limited purge fails without an error in the admin, and the affected pages keep their cached version until expiry. EmDash does not coalesce autosaves across requests or retry failed purges. Rejected tag purges are logged. However, @astrojs/cloudflare 14.3.1 discards the success result returned by cache.purge(): a refusal returned as success: false produces no EmDash error log and cannot be detected through Astro’s cache.invalidate() API.

During bulk edits, or with several editors working at once, choose a shorter maxAge you can accept for stale content, with swr to revalidate in the background. For example, maxAge: 3600 with swr: 60 treats a cached page as fresh for an hour, even if its purge failed, and allows serving it stale for a further 60 seconds while revalidation runs.

Browser caching is separate

The route cache can afford long TTLs because EmDash invalidates it; browser caches are not invalidated. EmDash hints supply purge tags, not automatic Last-Modified validators or Astro’s implicit Cache-Control: no-cache header. One entry’s modification time does not cover settings, related lists, or deleted entries, so using it as a page validator can keep an outdated body through conditional 304 responses.

Set browser caching with Astro.response.headers.set("Cache-Control", ...): use no-cache for a fresh check on each visit, or a short lifetime (minutes, not days). To enable conditional requests, supply your own lastModified hint whose timestamp advances whenever any dependency of the response changes.

For an entry’s displayed modification date, use entry.data.updatedAt rather than cacheHint.lastModified, which EmDash does not populate automatically.