Back to Blog
Cloud NativeJuly 5, 20264 min read

Automating Cloudflare Cache API Purging for Vercel Deployments

Learn how to use the Cloudflare Cache API to trigger instant asset invalidation after every Vercel deployment. Stop serving stale content at the edge.

VercelCloudflareEdge CachingDevOpsWeb PerformanceCache InvalidationDeployment

When you’re pushing updates to production, there’s nothing worse than seeing your users interact with stale assets. Vercel makes deployment incredibly simple, but if you’re sitting behind Cloudflare’s edge, that "instant" update doesn't always reach your end users immediately.

I’ve spent plenty of time debugging why a client’s CSS changes weren't appearing, only to realize the Cloudflare edge was still serving a cached version from three hours ago. To fix this, you need to sync your Vercel deployment pipeline with the Cloudflare Cache API.

The Problem with Default TTLs

By default, Cloudflare respects the Cache-Control headers sent by your origin. If you set a long TTL for static assets (which you should for performance), you’re effectively opting into a delay between deployment and visibility.

We initially tried lowering the TTL, but that just hammered our origin server and increased latency. A better approach involves cache invalidation strategies that allow us to keep long TTLs for speed while manually clearing the cache only when we actually push new code.

Using Vercel Deployment Hooks

Vercel offers deployment hooks that act as a trigger after a successful build. We can point this hook to a small serverless function or an edge worker that calls the Cloudflare API.

Here is the basic flow of the operation:

Flow diagram: Vercel Build → Deployment Hook; Deployment Hook → Cloudflare API; Cloudflare API → Clear Cache; Clear Cache → Edge Updated

To implement this, you’ll need your Cloudflare Zone ID and a scoped API Token with Zone.Cache Purge permissions.

Automating the Purge

You don't need a heavy backend to handle the request. A simple Node.js script triggered by a Vercel deployment hook works perfectly. I typically use a dedicated Next.js website & landing page development pattern, where I include an API route specifically for administrative tasks like this.

Here is a simplified version of the logic you’ll need:

JAVASCRIPT
// pages/api/purge-cache.js
export default async function handler(req, res) {
  if (req.method !== CE9178">'POST') return res.status(405).end();

  const response = await fetch(CE9178">`https://api.cloudflare.com/client/v4/zones/${process.env.CF_ZONE_ID}/purge_cache`, {
    method: CE9178">'POST',
    headers: {
      CE9178">'Authorization': CE9178">`Bearer ${process.env.CF_API_TOKEN}`,
      CE9178">'Content-Type': CE9178">'application/json',
    },
    body: JSON.stringify({ purge_everything: true }),
  });

  const data = await response.json();
  res.status(200).json(data);
}

Why "Purge Everything" vs. Tagged Purging

In the script above, I used purge_everything: true. It’s the "nuclear option." It’s simple, reliable, and ensures no user sees old code. However, it does cause a momentary spike in traffic to your origin as the cache repopulates.

If you have a massive site, you might prefer granular purging. By using Cloudflare Cache API with specific file paths or surrogate keys, you can surgically remove only the assets that changed. Just be aware that tracking these dependencies adds significant complexity to your build pipeline.

Hard-Won Lessons

I’ve learned the hard way that these hooks can fail. If the Cloudflare API is rate-limited or your token expires, the deployment will finish, but the cache will remain stale.

  • Always log the API response: Don't just fire and forget. Check the status code in your build logs.
  • Rate Limits: Cloudflare limits the number of purge requests per zone. Don't trigger this for every preview deployment; stick to production-only triggers.
  • Security: Ensure your API route is protected by a secret token, or only allow requests from Vercel’s known IP ranges.

If you are scaling up your architecture, you might also be interested in how we handle multi-region failover by syncing Vercel with Cloudflare to ensure that even if the primary region goes down, your cached assets remain available and consistent.

Frequently Asked Questions

Does purging everything hurt my SEO? Usually, no. If you do it once per production deployment, the impact is negligible. If you do it every time a developer makes a tiny commit to a branch, you’ll see performance degradation.

Can I purge by tag instead of purging the whole site? Yes, but you must ensure your origin server sends the Cache-Tag header in your HTTP responses. Cloudflare will then map those tags to your assets.

How often should I trigger an invalidation? Only on production deployments. For staging or preview environments, let the cache expire naturally or use a different, less aggressive strategy.

Automating your asset invalidation is a classic example of "do it once, reap the rewards forever." It removes the manual step of jumping into the Cloudflare dashboard every time you ship a hotfix. Just keep an eye on your API logs, and you’ll be fine.

Similar Posts