Route caching
Dieser Inhalt ist noch nicht in deiner Sprache verfügbar.
Hinzugefügt in:
astro@7.0.0
Beta
Astro provides a platform-agnostic API for caching responses from on-demand rendered pages and endpoints. Cache directives set in your routes are translated into the appropriate headers or runtime behavior depending on your configured cache provider.
Route caching builds on standard HTTP caching semantics, including max-age and stale-while-revalidate, with support for tag-based and path-based invalidation, config-level route rules, and pluggable cache providers that adapters can set automatically.
Configure caching
Section titled “Configure caching”Route caching requires a cache provider to determine how caching is implemented at runtime. A built-in in-memory provider is available, and custom providers can be implemented for advanced use cases and specific runtimes.
To enable this feature, set a cache provider in your Astro config:
import { defineConfig, memoryCache } from 'astro/config';import node from '@astrojs/node';
export default defineConfig({ adapter: node({ mode: 'standalone' }), cache: { provider: memoryCache(), },});You can then use Astro.cache in your .astro pages (or context.cache for API routes and middleware) to control caching per request. Cache defaults for groups of routes can also be defined declaratively in your config using routeRules.
Interacting with the cache
Section titled “Interacting with the cache”The cache object provides methods for setting cache options, invalidating entries, and checking the current cache state. This object is available in your .astro pages as Astro.cache, and in API routes and middleware as context.cache.
Checking if caching is enabled
Section titled “Checking if caching is enabled”When caching is not configured, cache.set(), cache.tags, and cache.options log a warning, and cache.invalidate() throws an error. To avoid this, wrap your caching logic in a conditional check using cache.enabled. Its value is always false when no provider is configured or in development mode.
---if (Astro.cache.enabled) { const tags = await getProductTags(Astro.params.id); Astro.cache.set({ maxAge: 3600, tags });}---Setting cache options
Section titled “Setting cache options”Call cache.set() with an options object to enable caching for the current response.
The following example caches a page for 2 minutes, serves stale content for 1 minute while revalidating, and tags the response for targeted invalidation:
---export const prerender = false; // Not needed in 'server' mode
Astro.cache.set({ maxAge: 120, swr: 60, tags: ['home'],});---
<html><body>Cached page</body></html>In API routes and middleware, use context.cache:
export function GET(context) { context.cache.set({ maxAge: 300, tags: ['api', 'data'], }); return Response.json({ ok: true });}Opting out of caching
Section titled “Opting out of caching”Call cache.set() with false to explicitly opt a request out of caching. This is useful when a matched route rule would otherwise cache the response:
---if (isPersonalized) { Astro.cache.set(false);}---Reading cache state
Section titled “Reading cache state”You can access the current accumulated cache options via cache.options. This is useful for debugging or when you want to conditionally modify caching based on the current state:
const { maxAge, swr, tags } = context.cache.options;Invalidating cache entries
Section titled “Invalidating cache entries”You can purge cached entries by tag or path using cache.invalidate(). This is useful for programmatically clearing cached content when it becomes stale, such as after a content update or user action.
The following example creates an API route that invalidates by tag and by path:
export async function POST(context) { // Invalidate all entries tagged 'data' await context.cache.invalidate({ tags: ['data'] });
// Invalidate a specific path await context.cache.invalidate({ path: '/api/data' });
return Response.json({ purged: true });}Tag-based invalidation removes all cached entries whose tags include any of the provided tags. Path-based invalidation is exact-match only (no glob or wildcard patterns).
Merge behavior
Section titled “Merge behavior”Multiple calls to cache.set() within a single request are merged according to the following rules:
- Scalar values (
maxAge,swr,etag): last-write-wins lastModified: most recent date winstags: accumulate across all calls
Middleware, layouts, content loaders, and page code can each contribute cache directives independently.
Dev mode behavior
Section titled “Dev mode behavior”In dev mode, the cache API is available so that route code does not need conditional checks, but no actual caching occurs. cache.enabled is false, and cache.set() and cache.invalidate() are no-ops. To test your caching locally, build then preview your site.
Route rules
Section titled “Route rules”Route rules allow you to define caching behavior for groups of routes declaratively in your config. This is useful for applying caching to large groups of routes at once.
The following example caches all API routes with stale-while-revalidate, product pages with a 1-hour freshness window, and blog posts for 5 minutes:
import { defineConfig, memoryCache } from 'astro/config';import node from '@astrojs/node';
export default defineConfig({ adapter: node({ mode: 'standalone' }), cache: { provider: memoryCache(), }, routeRules: { '/api/*': { swr: 600 }, '/products/*': { maxAge: 3600, tags: ['products'] }, '/blog/[...slug]': { maxAge: 300, swr: 60 }, },});The following route patterns are supported:
- Static paths:
/about,/api/health - Dynamic parameters:
/products/[id],/blog/[slug] - Rest parameters:
/docs/[...path] - Glob wildcards:
/api/*
Patterns use the same matching and priority rules as Astro’s file-based routing, so more specific patterns take precedence.
Per-route cache.set() calls merge with config-level route rules. Route code can override or extend the defaults set in config. For example, a route rule might set a default maxAge for all product pages, but individual pages can call cache.set() to customize or disable caching as needed.