Cache revalidation using Cache Tags

I came across a very impressive feature by Netlify (cache revalidation using cache tags). We cache something in a CDN (1 year) by tagging it with some custom cache tag. Then, for example, from a CMS after a post update, we purge the data with exactly the tags we need. Can we reproduce similar behavior on Cloudflare using the Purge Cached Content HTTP endpoint (for Free or Pro plans)?

https://developers.cloudflare.com/api/resources/cache/methods/purge/

Netlify Astro Example:

src/pages/books/[slug].astro:
---
import { client } from "../../lib/contentful";

const { slug } = Astro.params;
let book;

try {
  book = await client.getSingleBook(slug);
} catch (error) {
  return Astro.redirect("/404");
}
// The browser should always check freshness
Astro.response.headers.set("cache-control", "public, max-age=0, must-revalidate");

// The CDN should cache for a year, but revalidate if the cache tag changes
Astro.response.headers.set("netlify-cdn-cache-control", "s-maxage=31536000");

// Tag the page with the book ID
Astro.response.headers.set("netlify-cache-tag", slug);
---

src/pages/api/webhook.json.ts:
import { purgeCache } from "@netlify/functions";

export async function POST({ request }) {
  const body = await request.json();

  // See below for information on webhook security
  if (request.headers.get("X-Contentful-Webhook-Secret") !== process.env.CONTENTFUL_WEBHOOK_SECRET) {
    return new Response("Unauthorized", { status: 401 });
  }

  await purgeCache({ tags: [body.sys.id] });

  return new Response(`Revalidated entry with id ${body.sys.id}`, { status: 200 });
}


I currently have a project with a headless WordPress setup that uses the cache-control stale-while-revalidate (it's custom varnish + nginx), but this is not ideal for a CMS. I keep ttl short enough (1-10 seconds) so that the user sees the update as early as possible without overloading the origin server and have some cached responses at high load.
Interact with Cloudflare's products and services via the Cloudflare API
Was this page helpful?