Automatically purge Cloudflare Cache on new Deployment

Ivan Radunovic

Feb 29, 20244 min read
Automatically purge Cloudflare Cache on new Deployment

If you're not using Cloudflare for all of your sites, what are you doing?

The best feature they have is a built-in Proxy/CDN which will serve static assets from their edge network. If you're assets are correctly configured this will offload number of network requests to you server, reducing total traffic.

It's important to remove static assets requests from your server, or your server will need to serve every page, CSS or JS, which will increase number of processes and possibly consume all your workers.

There are cases online where people had to pay $100K bills for hosting static sites, since they did not have any CDN configured:

One case of huge Vercel bill

Cloudflare has a very generous free plan, and for 99% of sites that's all you need.

Cloudflare Proxy turn ON

When you add your site to Cloudflare in DNS settings there is on/off switcher for turning Cloudflare Proxy.

Cloudflare Proxy Example

This means Cloudflare will hide your Origin server IP, plus it'll cache all static assets. Inside Caching -> Configuration you can see all caching settings.

What happens when new application build is live

After compiling assets content of JS and CSS file could change. Some frameworks have cache busting which will force visitor browsers to download the latest version of assets.

Others don't have this feature or it may not function properly.

You want to avoid cases where old assets are cached since that could mess your entire app.

Manual Cache Purging

In Cloudflare Caching Configuration page there is a button which will purge entire cache or specified paths.

Purge Cache Manually

During development clicking this button is fine, but for production you need something on auto-pilot.

Automatic Cloudflare Cache Purging

Using Cloudflare API you can clear cache.

Options for calling Cache API

Purge_cache API is a simple POST request and it could be called from any programming language, framework or a simple CURL.

Example of Automatic Cache Purging using Laravel Command

In terminal lets create this command:

php artisan make:command CloudflarePurge

Inside the command class:

<?php

namespace App\Console\Commands;

use Illuminate\Support\Facades\Http;
use Illuminate\Console\Command;

class CloudflarePurge extends Command
{

    protected $signature = 'app:cloudflare-purge';

    protected $description = 'Purge Cloudflare Cache.';

    public function handle()
    {
        Http::withHeaders([
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . config('services.cloudflare.token')
        ])
        ->post('https://api.cloudflare.com/client/v4/zones/' . config('services.cloudflare.zone') . '/purge_cache', [
            'purge_everything' => true
        ]);
    }
}

This command relies on 2 configuration variables from services.php config file:

   'cloudflare' => [
        'token' => env('CLOUDFLARE_TOKEN'),
        'zone' => env('CLOUDFLARE_ZONE')
    ]

Zone ID is visible on domains Overview page, just scroll down and look into right sidebar.

Token could be created from Profile page, choose API tokens.

User API tokens Page

On this page create new token.

There is a number of options for API tokens I like to lock them based on the type of resource, zone, site and IP, example:

API token configuration

Calling purge command

If you're using something like Laravel Forge you can call command directly there.

In case you're deploying from GitHub actions it's a good idea to create protected route for purging cache, and then call that route from the Action.

Conclusion

In this tutorial you saw how easy it is to configure automatic cache purging using Cloudflare.

Now your sites will always serve fresh assets!

Share
Author Photo
Ivan Radunovic is a Senior Developer with over 11 years of experience in web development. His expertise are Laravel SaaS solutions. So far he developed or took part in 300+ Laravel projects.

More Laravel tutorials

Cloudflare Turnstile Laravel - Protect your app from bots

Turnstile will protect forms on sites from abusive bots. It's a hassle free alternative for Google ReCaptcha.

Feb 27, 2024 Ivan Radunovic

Login into Laravel application with a Magic link

Magic link authentication is a popular choice for login pages. User can request a link and click on it and he'll be authenticated.

Feb 24, 2024 Ivan Radunovic

Send Laravel notifications to Telegram messenger

Keeping track of your Laravel application is super important, integrating Laravel with Telegram messenger will help you gain better real-time insights.

Feb 21, 2024 Ivan Radunovic

Improving Laravel Loading Speed Using Redis Cache

Using Redis with Laravel application should be mandatory in the production. Redis greatly improves performance of Laravel apps if it's implemented in the right way.

Feb 20, 2024 Ivan Radunovic

Laravel SSO authentication with Google One Tap logins

Single sign-on authentication became a standard so we teach you how to implement it in your app. On top of that we'll show you how to integrate Google One Tap authentication flow also.

Feb 13, 2024 Ivan Radunovic

Google ReCaptcha in Laravel - Protect Laravel forms from bots

Learn how to integrate Google ReCAPTCHA into Laravel application, applies for types v2 and v3. All about I'm not a robot checkbox, invisible captcha and score based captcha.

Feb 12, 2024 Ivan Radunovic

Advanced querying with whereHas Method in Laravel Eloquent

The whereHas method in Laravel allows to filter models based on conditions of their related models, simplifying complex queries involving relationships.

Feb 05, 2024 Ivan Radunovic

Soft Delete in Laravel

With Laravel soft delete trait you can mark certain Eloquent model as deleted, and they will be removed from general queries. But you can query them with special methods.

Feb 04, 2024 Ivan Radunovic