Astro caching works in three layers. The browser cache keeps files on the visitor’s device, the CDN cache keeps copies at edge locations close to visitors, and the build cache keeps processed data between builds so deploys are faster. For a static Astro site, the rule is simple: cache everything in /_astro/ forever, because those file names are content-hashed, and let HTML revalidate on each visit so new deploys show up immediately.
This explainer covers each layer, the headers to set for static and on-demand pages, Astro 7’s route caching API, and how to keep builds fast.
Key Takeaways
- Files in
/_astro/are fingerprinted: serve them withCache-Control: public, max-age=31536000, immutable.- HTML should revalidate (
max-age=0, must-revalidate) so visitors always get the latest deploy.- On-demand pages set their own headers;
s-maxagewithstale-while-revalidatecaches them at the CDN.- Astro 7 adds a route caching API (
Astro.cache.set()androuteRules) with pluggable providers.node_modules/.astroholds the build cache; persist it in CI to skip reprocessing images and content.
The three Astro caching layers
| Layer | Where it lives | Controlled by | Affects |
|---|---|---|---|
| Browser cache | Visitor’s device | Cache-Control response headers |
Repeat visits and navigation |
| CDN cache | Host’s edge servers | Cache-Control, s-maxage, host settings |
Every visitor’s first request |
| Build cache | Build machine (cacheDir) |
Astro, plus your CI cache step | How long deploys take |
The first two decide how fast pages load. The third decides how fast you can ship changes. They’re independent, so it’s worth getting each right.
Browser caching for static Astro sites
A static build has two kinds of files with different needs.
Fingerprinted assets. CSS, JavaScript, optimized images and fonts processed by Astro land in dist/_astro/ with a content hash in the name, like index.DxQ2kP1a.css. When the content changes, the name changes. A cached copy can never be stale, so tell browsers to keep it for a year and never check again:
Cache-Control: public, max-age=31536000, immutable
HTML and unhashed files. index.html, /blog/post/, robots.txt, sitemap-index.xml and anything in public/ keep the same URL across deploys. If a browser caches them for a long time, visitors see old pages after you deploy. Let them be stored but revalidated:
Cache-Control: public, max-age=0, must-revalidate
With must-revalidate and an ETag or Last-Modified header from the host, the browser asks “has this changed?” and gets a tiny 304 Not Modified response when it hasn’t.
The asset pipeline explainer shows which files get hashed and which don’t.
Setting cache headers on static hosts
Most hosts already cache sensibly, but setting headers yourself makes the behavior explicit. On Cloudflare Pages and Netlify, add a _headers file to public/ so it’s copied into the build:
# public/_headers
/_astro/*
Cache-Control: public, max-age=31536000, immutable
/*
Cache-Control: public, max-age=0, must-revalidate
More specific rules win, so /_astro/* overrides the catch-all. On Vercel, the same rules go in vercel.json under headers. On your own server, configure Nginx or your web server with the same two patterns. The headers file tip and cache headers tip have copy-ready versions.
Don’t put long cache lifetimes on files in public/ that you might update, like og-image.png or favicon.svg. Either keep them short-lived or move them to src/ so they get hashed.
CDN caching for static pages
When a static site deploys, hosts like Cloudflare Pages, Netlify and Vercel distribute the files to their CDN and purge the old version automatically. HTML is served from the edge even with max-age=0 for browsers, because the CDN knows exactly when a deploy changes it. That’s why a static Astro site has a very low time to first byte worldwide without any cache configuration. The what a CDN does explainer covers this in depth.
Caching on-demand pages
Pages rendered per request (export const prerender = false with an adapter) aren’t cached anywhere by default. Every request runs your code. If the output is the same for many visitors, cache it at the CDN with a header:
---
// src/pages/products/[slug].astro
export const prerender = false;
const product = await getProduct(Astro.params.slug);
if (!product) return new Response(null, { status: 404 });
Astro.response.headers.set(
'Cache-Control',
'public, max-age=0, s-maxage=300, stale-while-revalidate=600'
);
---
<h1>{product.name}</h1>
max-age=0keeps browsers revalidating, so visitors don’t hold stale copies.s-maxage=300lets shared caches (the CDN) serve the page for five minutes.stale-while-revalidate=600lets the CDN serve a stale copy while it fetches a fresh one in the background, so no visitor waits on a slow render.
Never set public caching on pages that show personal data, such as account pages or carts. Use private, no-store for those. Some hosts also support CDN-Cache-Control or their own header to control the edge separately from browsers; check your host’s docs.
Astro 7 route caching
Astro 7 adds a platform-agnostic API for caching on-demand responses. You configure a cache provider (adapters can set one up automatically), then set rules per route or per request:
// astro.config.mjs
import { defineConfig, memoryCache } from 'astro/config';
import node from '@astrojs/node';
export default defineConfig({
adapter: node({ mode: 'standalone' }),
cache: { provider: memoryCache() },
routeRules: {
'/blog/[...path]': { maxAge: 300, swr: 60 },
'/products/[...slug]': { maxAge: 3600, tags: ['products'] },
},
});
Inside a route, Astro.cache.set() overrides the rule for that response (context.cache.set() in endpoints and middleware):
---
// src/pages/products/[slug].astro
export const prerender = false;
const product = await getProduct(Astro.params.slug);
Astro.cache.set({ maxAge: 600, swr: 120, tags: ['products', `product:${product.id}`] });
---
Tags make targeted purging possible. When a product changes, a webhook endpoint can call context.cache.invalidate({ tags: 'product:42' }) to drop just those entries instead of waiting for them to expire. Passing false to cache.set() turns caching off for a response. In dev, the cache object exists but doesn’t cache. The API is new in Astro 7, so check the Astro configuration reference for which providers your adapter supports.
Server islands and caching
Server islands let a cached static page include a component that renders per request. The page itself gets full CDN caching, and each island response can set its own Cache-Control. A stock indicator can cache for a minute; a user menu shouldn’t cache publicly at all. The server islands guide covers the details.
The Astro build cache
The third layer has nothing to do with visitors. During a build, Astro stores reusable work in cacheDir, which defaults to ./node_modules/.astro:
- Optimized images. Each transformed image is cached, so unchanged images aren’t reprocessed on the next build. On image-heavy sites this is the biggest saving.
- Content layer data. Loaded collection entries and their digests are stored, so unchanged content isn’t parsed again.
Locally this happens automatically. In CI, each build usually starts on a fresh machine, so the cache is lost unless you persist it. Cache node_modules/.astro between runs with your CI’s cache step (GitHub Actions actions/cache, or your host’s build cache, which some hosts handle for you). The CI build cache tip shows the GitHub Actions setup.
# .github/workflows/build.yml (excerpt)
- uses: actions/cache@v4
with:
path: node_modules/.astro
key: astro-${{ hashFiles('src/**', 'astro.config.mjs') }}
restore-keys: astro-
Clear the cache if a build behaves strangely after an upgrade; deleting node_modules/.astro is always safe and only costs a slower build.
An Astro caching checklist
/_astro/*served withmax-age=31536000, immutable.- HTML and
public/files served withmax-age=0, must-revalidate. - Personal on-demand pages marked
private, no-store. - Shared on-demand pages using
s-maxageplusstale-while-revalidate, or Astro 7 route caching with tags. node_modules/.astropersisted between CI builds.- Assets you update in place moved from
public/tosrc/so they’re hashed.
Komal themes build to static files with every component asset in /_astro/, so the two header rules above are all a deployed theme needs; browse the Astro themes or the Cloudflare deploy docs for the hosting side. MDN’s HTTP caching guide explains every header used here.
FAQ
How do I set cache headers for an Astro site?
For static sites, use your host’s headers configuration: a _headers file in public/ on Cloudflare Pages and Netlify, or vercel.json on Vercel. For on-demand pages, set Astro.response.headers in the page, or use Astro 7’s Astro.cache.set().
Why can Astro assets be cached forever?
Files in /_astro/ have a hash of their content in the file name. Any change produces a new file name, so a cached copy is never outdated and can be marked immutable.
Should I cache HTML pages in Astro?
Let browsers revalidate HTML (max-age=0, must-revalidate) so visitors see new deploys right away. CDNs still serve static HTML from the edge and purge it on deploy. For on-demand HTML, cache at the CDN with s-maxage only if the content isn’t personal.
What is node_modules/.astro?
It’s Astro’s default build cache directory (cacheDir). It stores optimized images and content layer data so later builds skip unchanged work. It’s safe to delete; Astro rebuilds it.
How do I clear the cache after deploying an Astro site?
Static hosts purge their CDN cache automatically on each deploy, and hashed assets get new URLs. If visitors still see old HTML, check that HTML isn’t served with a long max-age.