Clearing Cloudflare cache in Gulp

Three days ago (yes, still going!) I published a post about saving time with FTP in Gulp, where I added a “deploy” method which uploaded the final build items via FTP.

I would always recommend using Cloudflare (you may remember me mentioning them before) as a reverse proxy service protecting your origin server from malicious traffic, DDoS attacks, etc..  They provide a great service and their Free tier includes a surprising amount of functionality.

Cloudflare is particularly good when you’re creating a fairly static site, as can often be the case especially when we’re using a development workflow like we are with Gulp.  But what’s the point of automatically deploying if you then have to log into Cloudflare in order to clear the cache and pick up the new assets?

Luckily Cloudflare has a great API, and we can use the request package on NPM to access it.  Now there is a gulp-cloudflare package but when I tested it, it was out of date and didn’t work – it hadn’t been updated for 4 years.

As always, first we need to install the request package using NPM…

npm install --save-dev request

Then (if you’re not automatically requiring plugins) we can to require it at the top of our “gulpfile.js” file…

var request = require("request");

Then we want to add a new task to handle the API call…

var cf = function() {
  return request.post({
    url: 'https://api.cloudflare.com/client/v4/zones/MY-ZONE-ID/purge_cache',
    headers: {
      'X-Auth-Email': 'EMAIL-ADDRESS',
      'X-Auth-Key': 'GLOBAL-API-KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({'purge_everything': true})
  });
};

The API states that we should be using a POST for this and that “purge_everything” is a required attribute.  There are some variables here that need to be properly populated for your account…

  • MY-ZONE-ID – this is the zone ID for your account and can be found on the first page of your Cloudflare dashboard
  • EMAIL-ADDRESS – this is the email address associated with your Cloudflare account
  • GLOBAL-API-KEY – this can also be found on the first page of your Cloudflare dashboard (you can use a user service key instead which has a more reduced scope, but for simplicity I’ve used the global key)

Finally we can add this to our “deploy” method we built previously…

exports.default = gulp.series(gulp.parallel(php,js,img,css),final);
exports.deploy = gulp.series(gulp.parallel(php,js,img,css),final,ftp,cf);

This means that if I call “gulp deploy” then the project will be built, deployed via FTP, and then the Cloudflare cache will be purged, allowing all of the newly uploaded files to be picked up straight away.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.