Caching the WordPress REST API for Astro: Cloudflare, Purging, and Safe Build Fallbacks

In this article (11)
A headless WordPress website can give editors a familiar publishing experience while Astro generates a fast, mostly static frontend. But this architecture introduces a dependency: when Astro builds the site, it may need to fetch content from WordPress.
If the WordPress server is overloaded, the API returns unnecessary data, or requests fail during deployment, the build can slow down or fail. Cloudflare edge caching can reduce repeated requests to the WordPress origin, but it is only one part of a dependable solution.
This guide explains how to optimize the requests first, cache public API responses safely, invalidate cached content when it changes, and decide whether a fallback content snapshot is appropriate. The examples assume an Astro static site and a WordPress installation at https://cms.example.com proxied through Cloudflare.
What this guide does not promise: A particular API response time, a “sub-second” Astro build, or guaranteed successful deployment. Those outcomes depend on the hosting environment, request volume, content, build process, and cache hit rate.
1. Understand what is—and is not—being cached
In a typical static deployment, data flows like this:
WordPress admin → Published WordPress posts
|
v
WordPress REST API (JSON)
^
| cache miss
|
Astro build → Cloudflare edge cache
|
cached JSON
|
v
Generated HTML
|
v
Static site hosting
There are three distinct layers:
- WordPress/origin caching can reduce the work required to generate an API response.
- Cloudflare edge caching can serve an eligible, previously cached response without asking WordPress to generate it again.
- Astro’s static output is the HTML generated at build time. Refreshing the API cache does not update already deployed HTML; the static site normally needs another build and deployment.
Cloudflare does not cache JSON responses under its default file-extension-based behavior. To cache selected REST API responses, you must configure caching explicitly. See Cloudflare’s default cache behavior and Astro’s WordPress integration guide.
2. Measure before making changes
Start with the actual API URL your build calls. For example:
curl -sS -D - -o /dev/null \
'https://cms.example.com/wp-json/wp/v2/posts?per_page=50&page=1&_fields=id%2Cslug%2Cmodified%2Ctitle'
Inspect the response headers, especially:
CF-Cache-Status: Cloudflare’s decision, such asHIT,MISS,BYPASS, orDYNAMIC.Age: how long a cached object has been stored, when available.Cache-Control: the origin’s or intermediary’s caching instructions.X-WP-TotalPages: the number of pages in a paginated WordPress collection.
Repeat the same request to check for a possible cache hit. A MISS is normal on the first request or after an eviction; a BYPASS suggests caching rules or response headers need investigation. Cache behavior can differ between Cloudflare locations, so one request is not a performance benchmark.
For reproducible before-and-after testing, record response times from multiple runs and compare them with your full Astro build duration. Track API fetch time separately from total build time. See Cloudflare’s cache status guidance.
3. Optimize WordPress REST API requests first
Before adding another cache layer, reduce unnecessary data transfer.
Request only the fields you need
An archive page may only need a post’s ID, slug, modified date, and title:
/wp-json/wp/v2/posts?per_page=50&page=1&_fields=id,slug,modified,title
WordPress supports _fields for selecting properties. This can reduce response size and some server-side processing. It also supports _embed for related objects, but embedding all available resources can add work and payload size. If you need only featured media or taxonomy information, select the relevant relationships instead of requesting everything blindly.
Important: When combining _embed and _fields, include _links and _embedded in the fields selection; otherwise embedded resources may not appear as expected. See WordPress REST API global parameters.
Handle pagination properly
The posts endpoint usually returns 10 posts by default, and per_page is normally limited to 100. It exposes X-WP-TotalPages, which your build can use to retrieve every page. Fetching only page one can silently omit older posts from your Astro routes.
This TypeScript utility demonstrates pagination, basic response validation, a timeout, and limited retries for transient failures:
// src/lib/wordpress.ts
export interface WpPost {
id: number;
slug: string;
modified: string;
title: { rendered: string };
}
const origin = import.meta.env.WP_CMS_ORIGIN;
function isWpPost(value: unknown): value is WpPost {
if (typeof value !== 'object' || value === null) return false;
const post = value as Record<string, unknown>;
const title = post.title as Record<string, unknown> | undefined;
return (
typeof post.id === 'number' &&
typeof post.slug === 'string' &&
typeof post.modified === 'string' &&
typeof title?.rendered === 'string'
);
}
class NonRetryableHttpError extends Error {}
async function fetchWithRetry(url: URL): Promise<Response> {
for (let attempt = 0; attempt < 3; attempt++) {
try {
const response = await fetch(url, {
signal: AbortSignal.timeout(8000),
});
if (response.ok) return response;
// Retrying most 4xx errors will not fix a bad request.
if (response.status >= 400 && response.status < 500 &&
response.status !== 429) {
throw new NonRetryableHttpError(`HTTP ${response.status}`);
}
throw new Error(`Temporary HTTP ${response.status}`);
} catch (error) {
if (error instanceof NonRetryableHttpError) throw error;
if (attempt === 2) throw error;
await new Promise((resolve) =>
setTimeout(resolve, 500 * 2 ** attempt)
);
}
}
throw new Error('Unexpected retry state');
}
export async function fetchPublishedPosts(): Promise<WpPost[]> {
if (!origin) throw new Error('Missing WP_CMS_ORIGIN');
const posts: WpPost[] = [];
let totalPages = 1;
for (let page = 1; page <= totalPages; page++) {
const url = new URL('/wp-json/wp/v2/posts', origin);
url.searchParams.set('per_page', '50');
url.searchParams.set('page', String(page));
url.searchParams.set('_fields', 'id,slug,modified,title');
const response = await fetchWithRetry(url);
const pageCount = Number(response.headers.get('X-WP-TotalPages'));
if (!Number.isInteger(pageCount) || pageCount < 1) {
throw new Error('Invalid or missing WordPress pagination header');
}
const data: unknown = await response.json();
if (!Array.isArray(data) || !data.every(isWpPost)) {
throw new Error('Unexpected WordPress API response');
}
totalPages = pageCount;
posts.push(...data);
}
if (new Set(posts.map((post) => post.id)).size !== posts.length) {
throw new Error('Duplicate post IDs across API pages');
}
return posts;
}
Set WP_CMS_ORIGIN=https://cms.example.com in the Astro build environment. This variable does not need a PUBLIC_ prefix because the function is intended for build-time use, not browser execution. The example deliberately fetches only public post fields and contains no WordPress credentials.
This is a starting point, not a full sync engine. If posts change while you are paginating, a collection can move between pages; high-volume publishing systems may need a stable export or additional consistency checks. Rate limits (429) may also require honoring Retry-After rather than using only a fixed retry schedule. See WordPress pagination.
4. Configure Cloudflare caching for public endpoints only
A risky approach is enabling “cache everything” for /wp-json/*. The WordPress REST API includes endpoints used by authenticated editors, plugins, account features, and integrations. Never cache personalized, preview, private, or authenticated responses in a shared public cache.
For a small, read-only blog, begin with the one public collection route the build actually needs:
Hostname: cms.example.com
URI path: /wp-json/wp/v2/posts
In Cloudflare → Caching → Cache Rules:
- Add an explicit bypass policy for authenticated requests (for example, requests with an
Authorizationheader or WordPress login cookies), preview/edit requests, and any route with private data. Verify the rule order against your other Cloudflare rules. Test with a logged-in editor session before deploying the configuration. - Add a narrowly scoped rule for the public posts collection. Set Cache eligibility → Eligible for cache. Don’t automatically include all
/wp-json/endpoints or post revision/autosave routes. - Keep relevant query parameters in the cache key.
page=1,page=2, different_fieldsvalues, and slug filters can return different results. Ignoring them could serve the wrong content. - Decide on freshness: a short edge TTL, such as five minutes as a starting policy, may be appropriate for verified-public content. Prefer origin caching headers when reliable. If the origin responds with
private,no-store,no-cache, or cookies, investigate why before considering any Cloudflare setting that overrides those instructions. - Test both anonymous and authenticated requests, then confirm that cached responses contain only public content.
Important nuance: Cloudflare’s Edge TTL settings can override origin Cache-Control directives, including no-store, in some configurations. So “eligible for cache” plus a forced TTL is not inherently safe. A dedicated public-content endpoint or an explicitly allowlisted route is much easier to audit than a blanket WordPress API rule. Read Cloudflare Cache Rules and cache response behavior.
5. Plan cache invalidation before increasing TTLs
A cached response can remain stale after an editor changes a post. And WordPress changes can affect more than one URL:
| Content event | Possible affected responses |
|---|---|
| Publish a post | Post lists, paginated archives, category lists |
| Update a post | Its detail endpoint, archives, embedded data |
| Unpublish or delete a post | Existing post URLs, collections, pagination |
| Change a category or featured image | Post responses and related term/media data |
Purging one hardcoded URL like posts?slug=example is not enough if Astro requests different query combinations or multiple archive pages.
For small deployments, purge by URL prefix is a practical alternative. Cloudflare made all purge methods, including prefix purges, available across plans in 2025 (subject to plan-dependent limits). For example, this API request invalidates cached URLs beginning with the posts route:
# Set CF_ZONE_ID and CF_API_TOKEN in your shell or CI secrets.
curl --fail-with-body -sS -X POST \
"https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/purge_cache" \
-H "Authorization: Bearer ${CF_API_TOKEN}" \
-H 'Content-Type: application/json' \
--data '{
"prefixes": ["cms.example.com/wp-json/wp/v2/posts"]
}'
The prefix contains the hostname and path only—not https:// and not a query string. It covers multiple page, _fields, and slug variations, but also invalidates other cached URLs beginning with that same prefix. If you also cache /wp-json/wp/v2/categories or /media, decide how those resources will be purged separately.
Use a Cloudflare API token with the minimum needed Cache Purge permission, store it in server-side secrets, and inspect the API’s success response. A successful purge request means Cloudflare accepted the operation; verify the next request and its cache status separately. See Cloudflare purge-by-prefix documentation and the Purge Cache API.
Trigger invalidation when WordPress content changes
In an automated setup, a content-change event can enqueue two operations:
WordPress publish / update / unpublish
|
v
Background job / webhook
/ \
v v
Purge relevant Trigger Astro
Cloudflare URLs deployment
For WordPress-side integration, wp_after_insert_post fires after WordPress has saved a post, its terms, and metadata. You still need to handle deletes and relevant taxonomy/media changes explicitly. Avoid putting slow, synchronous network calls directly into an editor’s save request; a background queue or deployment automation is easier to retry and monitor.
Ordering matters: Invalidate the stale API response before the build fetches content. Otherwise, a new Astro deployment can accidentally compile old content from a still-warm cache. If your frontend is fully static, purging Cloudflare alone does not publish the change; rebuild and deploy the frontend too.
6. Decide whether a JSON snapshot fallback is appropriate
A snapshot is a copy of previously fetched public content, committed to the repository or stored as a versioned build artifact. It can allow an Astro build to proceed during a temporary WordPress outage—but it introduces the possibility of deploying stale or withdrawn content.
There are two reasonable policies:
- Fail the new build: Usually best for sites where freshness, content removal, or accuracy is important. On deployment platforms that preserve the previous successful release, the live site stays on the last good version.
- Allow a bounded fallback: Potentially suitable for a low-risk, mostly evergreen blog. Only use it if the snapshot is recent, complete, public, and explicitly permitted in the build configuration.
Here is an example with a 24-hour maximum snapshot age and an opt-in build flag. The JSON file is assumed to contain { "generatedAt": "<ISO date>", "posts": [...] } and to have been generated only after a successful, validated fetch:
// src/lib/wp-build-data.ts
import snapshotJson from '../data/wp-posts.snapshot.json';
import { fetchPublishedPosts, type WpPost } from './wordpress';
const MAX_SNAPSHOT_AGE_MS = 24 * 60 * 60 * 1000;
interface Snapshot {
generatedAt: string;
posts: WpPost[];
}
export async function getPostsForBuild(): Promise<WpPost[]> {
try {
return await fetchPublishedPosts();
} catch (error) {
if (import.meta.env.ALLOW_WP_SNAPSHOT_FALLBACK !== 'true') {
throw error;
}
const snapshot = snapshotJson as Snapshot;
const age = Date.now() - Date.parse(snapshot.generatedAt);
if (!Number.isFinite(age) || age < 0 ||
age > MAX_SNAPSHOT_AGE_MS || !Array.isArray(snapshot.posts)) {
throw new Error('WordPress unavailable and snapshot is invalid or stale');
}
console.warn('Using a previously approved WordPress snapshot');
return snapshot.posts;
}
}
The fallback is not a promise of build success. A snapshot can be invalid, too old, incomplete, or unsuitable after an urgent content removal. The example only checks basic snapshot metadata; in production, validate its complete record schema and publication status at snapshot creation, record the snapshot version in build logs, and alert editors when fallback data is deployed.
Keep snapshots out of the browser unless they are intentionally public. Never commit private posts, draft content, WordPress credentials, or authenticated API responses.
For a site that publishes time-sensitive articles, failing the new deployment is usually safer than silently rebuilding with old data.
7. Use the data inside an Astro static route
Astro’s getStaticPaths() can turn WordPress post slugs into static pages. For example:
---
// src/pages/blog/[slug].astro
import { getPostsForBuild } from '../../lib/wp-build-data';
export async function getStaticPaths() {
const posts = await getPostsForBuild();
return posts.map((post) => ({
params: { slug: post.slug },
props: { post },
}));
}
const { post } = Astro.props;
---
<main>
<h1>{post.title.rendered}</h1>
<p>Post ID: {post.id}</p>
</main>
This minimal route demonstrates static path generation; it does not yet fetch or display full article content. In a real blog, the title and content may contain WordPress-rendered HTML. Understand and sanitize the content before using Astro’s set:html directive for arbitrary markup. To show a full post, fetch or include the appropriate content field as part of your validated data model.
Also avoid fetching the entire WordPress collection independently in many different components. Centralize your build-time data access or use a content layer so repeated API calls do not undo the advantages of caching.
8. Test the complete publication workflow
Use this checklist before relying on the setup in production:
- Request the same public posts URL twice and inspect
CF-Cache-Status. - Confirm the API returns all pages, not just the default first 10 posts.
- Confirm different
pageand_fieldsqueries return the correct records. - Check logged-in, authenticated, private, preview, and plugin endpoints are not stored in the shared cache.
- Publish a post; verify invalidation occurs before the Astro rebuild fetches content.
- Edit, unpublish, and delete posts; confirm generated pages and archives update correctly after deployment.
- Simulate an origin timeout and verify retries, build failure behavior, and any opt-in snapshot policy.
- Compare repeated API response times and total Astro build times, without assuming they improve by the same percentage.
- Check Cloudflare and WordPress logs for failed purge operations and unexpected API responses.
9. Common mistakes and trade-offs
Caching the whole WordPress REST API: Dangerous because authenticated and extension-provided routes may expose personalized data. Cache only explicitly audited public responses.
Forcing a TTL over no-store: Can override origin intent. Find out why the origin marked a response uncacheable before changing its behavior.
Ignoring query strings in the cache key: page, slug, and _fields often change the response. Ignoring them can return unrelated or incomplete content.
Purging without rebuilding: A correct API cache does not rewrite already deployed static HTML.
Rebuilding before purging: Astro may compile stale cached JSON into a new deployment.
Treating fallback data as always safe: Withdrawn, corrected, or time-sensitive content must not be silently republished from an old snapshot.
Measuring only a cache HIT: A fast cached API response is useful, but the important outcome is whether the complete publishing workflow is reliable and meets your actual build-time requirements.
Conclusion
For a headless WordPress and Astro site, the best starting point is not an aggressive Cloudflare rule. It is a small set of deliberate decisions: request only necessary data, paginate correctly, cache only verified-public responses, preserve meaningful query parameters, invalidate the right resources, and rebuild static pages after content changes.
Cloudflare can reduce repeated load on WordPress and improve API fetch latency. A carefully governed snapshot can sometimes help with temporary outages. Neither feature guarantees a fast build, immediate content freshness, or protection from every deployment failure.
That trade-off is precisely why a measurable, security-conscious approach is more useful than a blanket “cache everything” setting.


