Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 37 ยท Performance and Deployment

Prefetching and Caching Strategies in Astro

Make navigation feel instant with Astro prefetch strategies (hover, tap, viewport, load), set HTTP cache headers, and combine CDN caching with SSR.

The fastest request is the one that is already finished when the user clicks. Prefetching downloads the next page in the background before it is needed, and caching makes repeat downloads unnecessary. Used together they make a multi-page Astro site feel like an app, without a heavy JavaScript framework.

Enabling prefetch

Turn it on in the config:

JavaScript
// astro.config.mjs
export default defineConfig({
  prefetch: true,
});

With prefetch: true, links marked data-astro-prefetch are prefetched. Use the attribute on individual links, or prefetch all links:

JavaScript
export default defineConfig({
  prefetch: {
    prefetchAll: true,
    defaultStrategy: 'viewport',
  },
});
ASTRO
<a href="/pricing" data-astro-prefetch>Pricing</a>
<a href="/blog" data-astro-prefetch="viewport">Blog</a>
<a href="/huge-report" data-astro-prefetch="false">Report</a>

If you use <ClientRouter />, prefetching is already enabled with the hover strategy as default for all links.

The four strategies

Strategy Prefetches when Cost Best for
tap The user starts to press the link (mousedown/touchstart) Lowest Large pages, metered connections
hover (default) The pointer enters the link, or it receives keyboard focus Low Most navigation menus
viewport The link scrolls into view Medium Short lists of important links
load The page has loaded Highest A few "next step" links

hover typically gives 100-300 ms of head start (mouse movement before the click). viewport gives much more but may fetch pages nobody visits. On touch devices there is no hover, so tap or viewport matter more.

Prefetching the wrong thing wastes bandwidth. Avoid load on lists of dozens of links. Do not prefetch pages with side effects (logout URLs that change state on GET are an anti-pattern anyway).

How prefetching works

Astro adds a <link rel="prefetch"> for the URL (or uses fetch with low priority where <link rel="prefetch"> is not supported) and respects the Save-Data header and slow connections by skipping viewport and load prefetching. The browser stores the result in its HTTP cache; when the user clicks, the HTML comes from cache.

Important: prefetching only helps if the response is cacheable. If the server sends Cache-Control: no-store, the prefetched copy is thrown away.

You can also trigger it from code:

ASTRO
<script>
  import { prefetch } from 'astro:prefetch';
  document.querySelector('#next')?.addEventListener('mouseenter', () => prefetch('/next-step'));
</script>

HTTP caching basics

A response can carry:

  • Cache-Control: max-age=N: the browser reuses it for N seconds without asking.
  • s-maxage=N: same, for shared caches (CDNs).
  • no-cache: must revalidate before use (often a quick 304).
  • no-store: never keep it.
  • immutable: will never change during its max-age.
  • stale-while-revalidate=N: serve old content immediately and refresh in the background.
  • ETag / Last-Modified: let the client ask "has it changed?" and receive a tiny 304.

A sensible policy for an Astro site:

Resource Header
/_astro/* (hashed) public, max-age=31536000, immutable
Images in public/ public, max-age=86400 (or hash them by using src/)
Static HTML public, max-age=0, must-revalidate (or short s-maxage on a CDN)
SSR pages, public public, s-maxage=300, stale-while-revalidate=600
SSR pages, personal private, no-store

Static hosts such as Netlify and Cloudflare Pages let you set these in a _headers file in public/:

TEXT
/_astro/*
  Cache-Control: public, max-age=31536000, immutable

/*
  X-Content-Type-Options: nosniff

Caching SSR responses

For server-rendered pages you set headers yourself:

ASTRO
---
export const prerender = false;
const posts = await fetchPopularPosts();

Astro.response.headers.set(
  'Cache-Control',
  'public, max-age=60, s-maxage=600, stale-while-revalidate=86400',
);
---

Meaning: browsers keep it a minute; the CDN for ten minutes; after that the CDN may serve a stale copy for up to a day while it fetches a fresh one. The trade-off is freshness against server load. Never mark pages with personal data as public, and avoid Set-Cookie on responses you want a CDN to cache, because many CDNs refuse to cache those.

Combining ideas: make the page cacheable with a short TTL, and use server islands (server:defer) for the personalised parts, so you get CDN speed with fresh user data.

Cache invalidation

Hashed assets never need invalidation. For HTML on a CDN you either use a short TTL, or purge on deploy (Cloudflare, Netlify and Vercel can purge automatically on each deploy). A widely used trick: make HTML always revalidate (max-age=0, must-revalidate) because 304 responses are cheap, while hashed assets are cached forever.

Try it: a prefetch simulator

The stand-in models a browser cache, a prefetch on hover and the effect on click time. Network cost is simulated in milliseconds.

JS Hover prefetch

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Try it: pick the Cache-Control header

A stand-in "policy engine" that applies the table above and warns about risky combinations.

JS Cache policy checker

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which prefetch strategy waits until the user presses on the link?

    tap fetches on mousedown or touchstart, which is the cheapest strategy but gives the smallest head start.
  2. 2. Why can Cache-Control: no-store defeat prefetching?

    Prefetching relies on the HTTP cache. A response that must not be stored cannot be reused on click.
  3. 3. What is a safe header for hashed files in /_astro/?

    The content hash in the file name changes with content, so the file can be cached for a year.
  4. 4. What does stale-while-revalidate=600 allow?

    Caches may answer immediately with the stale response and refresh it in the background.

Summary

  • Turn on prefetch and choose a strategy per link; hover is a good default, tap is lightest, viewport and load cost more.
  • Prefetch only helps when responses are cacheable.
  • Hash assets and cache them forever; make HTML revalidate; give public SSR pages s-maxage with stale-while-revalidate; mark personal pages private, no-store.
  • Combine cached pages with server islands for personalised pieces.

Next: Deploying an Astro Site