Skip to content

MKI

Astro 7 gives on-demand pages a real caching API

Astro 7 stabilizes route caching and adds an Advanced Routing entrypoint, so on-demand pages finally get cache-control without host-specific hacks.

Caching an on-demand page has always meant learning your host’s dashboard, not your framework. Set a header wrong on Vercel and it means something different than the same header on Netlify or a plain Node server. Astro 7, released June 22, 2026, changes that: route caching, which shipped experimentally in Astro 6, is now stable, and it comes with a single API that works the same way regardless of where the site runs. The same release also stabilizes Advanced Routing, a src/fetch.ts entrypoint that gives a project full control over Astro’s request pipeline.

Neither feature is flashy on its own. Together they solve a problem every team running Astro with on-demand rendering eventually hits: caching logic and pipeline ordering that live in your host’s config instead of your codebase, untested and undocumented until someone forgets how it works.

We maintain Astro sites for clients that mix static and on-demand rendering, so a stable, portable caching API is the kind of change we track closely.

What changed

Astro’s own release notes describe route caching as “a single platform-agnostic API for caching: set directives in your routes, and Astro handles the rest wherever you deploy.” It configures a cache provider once in astro.config.mjs, then exposes Astro.cache in pages and context.cache in API routes and middleware to set caching behavior per response, on top of standard HTTP caching semantics. Astro ships a built-in memoryCache() provider out of the box, and Astro 7 adds experimental CDN-backed providers for three hosts: cacheNetlify() from @astrojs/netlify/cache, cacheVercel() from @astrojs/vercel/cache, and cacheCloudflare() from @astrojs/cloudflare/cache.

Advanced Routing is the second half of the story. Astro’s blog post frames the motivation directly: “If you needed auth to run before Actions, logging to wrap only page rendering, or a non-Astro API to handle some requests first, you had to work around the pipeline instead of composing it directly.” Adding a src/fetch.ts file exports a standard fetch handler — the same request-in, response-out pattern used by Cloudflare Workers, Deno, and Bun — and the API is Hono-compatible, so a project can drop in Hono middleware directly.

Both features were experimental flags in Astro 6 (experimental.cache and experimental.advancedRouting). The v7 upgrade guide is explicit about the migration: “If you were using this feature, update your config to move cache and routeRules out of the experimental block.” No other API changes — what worked experimentally keeps working, just promoted to the top level of the config.

The gap this closes

Before Astro 7, caching an on-demand Astro response meant reaching for whatever your host offered: a Cache-Control header set by hand, a platform-specific edge config file, or a CDN rule configured outside the codebase entirely. None of that was portable. A caching strategy built around Vercel’s edge config didn’t transfer to a Netlify migration, and it definitely didn’t transfer to a plain Node deployment on a VPS. Worse, none of it was testable the way application code is — you couldn’t write a unit test for a header that lived in a dashboard.

Routing composition had a parallel problem. Astro’s middleware, Actions, sessions, and i18n all grew up as separate systems layered onto file-based routing over several major versions. Each one worked well in isolation, but ordering them against each other — auth before Actions, logging around page rendering only, a non-Astro API fielding some paths first — meant fighting the built-in pipeline order rather than declaring your own.

Both gaps share a root cause: the request pipeline and the cache layer were things Astro ran on your behalf, not things you could see or shape from application code. That’s a reasonable default for a framework aimed at static sites, but it stops working once a project takes on real server-side logic — the exact direction more Astro projects have moved as on-demand rendering, Actions, and sessions matured.

How the caching API actually works

The core pattern is a set call with three levers: maxAge for how long a response is fresh, swr for stale-while-revalidate, and tags for targeted invalidation later.

---
Astro.cache.set({
maxAge: 120, // Cache for 2 minutes
swr: 60, // Serve stale for 1 minute while revalidating
tags: ['products'], // Tag for targeted invalidation
})
---

For rules that apply across a whole section of a site, routeRules in the config keeps caching declarative and out of individual route files:

export default defineConfig({
cache: { provider: memoryCache() },
routeRules: {
'/blog/[...path]': { maxAge: 300, swr: 60 },
},
})

Invalidation is where the API earns its keep for content-driven sites. cache.invalidate() can purge by tag or by exact path, which maps cleanly onto a CMS webhook: a content update comes in, the handler invalidates every response tagged with that entry, and the next request rebuilds it — no full redeploy required.

export const POST: APIRoute = async ({ request, cache }) => {
const { slug } = await request.json()
await cache.invalidate({ tags: ['products'] })
await cache.invalidate({ tags: [`products:${slug}`] })
await cache.invalidate({ path: `/products/${slug}` })
return new Response('Revalidated')
}

The tightest integration is with Astro’s live content collections: a live loader can attach a cache hint — tags for invalidation, a last-modified time for freshness — directly to the data it returns, and passing that entry straight to Astro.cache.set(entry) lets Astro read the hint without any manual header work.

Where the CDN providers change the economics

The built-in memoryCache() provider works with the Node adapter and stores responses in memory on the server. The three new CDN providers push the same caching directives to the host’s own edge network instead, which changes what a cache hit costs: a hit is served straight from the CDN without invoking the server function at all. For a team paying per-invocation on a serverless host, that’s not just a latency win, it’s a bill that grows more slowly under load.

The catch is that all three providers are explicitly experimental in this release. Astro’s blog notes that “in a future release, these providers will be enabled automatically, but during the experimental phase you should add them manually” — importing the provider for your adapter and setting it in cache.provider yourself. Every provider still exposes the same Astro.cache, routeRules, and cache.invalidate() surface; only the translation to the platform’s native cache-control headers and purge API changes underneath.

That “experimental” label is worth taking seriously before you build a critical path on it. The API contract Astro documents is stable — set, routeRules, invalidate() — but the provider implementation underneath each adapter can still change shape before it graduates. A reasonable posture for a production site: adopt the stable core API now, since that’s what you’ll keep either way, and treat the specific CDN provider you wire up as something to revisit once Astro’s release notes say it’s no longer experimental.

What Advanced Routing adds on top

Advanced Routing matters here because caching decisions rarely live alone — they need to run in the right order relative to auth, logging, and any non-Astro API a project fronts. src/fetch.ts gives you that ordering directly, composing Astro’s own pieces as middleware:

import { Hono } from 'hono'
import { actions, middleware, pages, i18n } from 'astro/hono'
import { auth } from './middleware/auth'
import { timing } from './middleware/timing'
const app = new Hono()
app.use(i18n())
app.use(auth()) // Auth runs before actions, no unauthenticated calls
app.use(actions())
app.use(middleware())
app.use(timing()) // Timing wraps only page rendering
app.use(pages())
export default app

A simpler version just forwards specific paths before falling back to Astro entirely, which is the pattern for fronting a separate backend API from the same Astro deployment:

import { astro, FetchState } from 'astro/fetch'
export default {
fetch(request: Request) {
const state = new FetchState(request)
if (state.url.pathname.startsWith('/api')) {
const url = new URL(state.url.pathname + state.url.search, 'https://backend-api.example.com')
return fetch(new Request(url, request))
}
return astro(state)
},
}

Projects that don’t add a src/fetch.ts file see no change in behavior at all — Astro’s pipeline runs exactly as it did before.

The one breaking change worth checking before you upgrade

src/fetch.ts is now a reserved file name, the same way src/middleware.ts already was. If a project happens to already have a file at that path for an unrelated purpose, Astro will try to parse it as an Advanced Routing config after upgrading, which the upgrade guide flags as a source of “unexpected errors.” The fix is a one-line config change — set fetchFile to a different path, or null to disable Advanced Routing outright — or simply rename the existing file. It’s a five-minute check, but it’s the kind of thing that only surfaces after the upgrade lands, so it’s worth grepping for src/fetch.ts before running npx @astrojs/upgrade rather than after.

What we’d do about it

Neither feature touches a fully static build. This site is static by design — no adapter, no on-demand rendering — so route caching and Advanced Routing don’t apply to it directly, and nothing here changes how we ship it.

They matter for the other half of what we build: client projects with on-demand rendering, whether that’s a storefront with per-user pricing, a dashboard behind auth, or anything served through the Cloudflare Workers migration we wrote about earlier this month. For those, our next Astro upgrade includes a deliberate pass: check for an existing src/fetch.ts, move any experimental cache or routeRules config out of the experimental block, and pick one cacheable route — a product listing, a marketing page rendered on demand for A/B testing — to wire up with Astro.cache and a CDN provider before rolling it out further. Testable cache behavior in the codebase beats a header nobody remembers setting in a dashboard.

If you’re running an Astro site with server-rendered routes and want a second opinion on where caching would actually pay off, or you’re weighing a performance pass on an existing site, get in touch.

Sources