Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clearing cloudflare cache programmatically

I am trying to clear the cloudflare cache for single urls programmatically after put requests to a node.js api. I am using the https://github.com/cloudflare/node-cloudflare library, however I can't figure out how to log a callback from cloudflare. According to the test file in the same repo, the syntax should be something like this:

//client declaration:

    t.context.cf = new CF({
        key: 'deadbeef',
        email: '[email protected]',
        h2: false
      });

//invoke clearCache:

           t.context.cf.deleteCache('1', {
            files: [
              'https://example.com/purge_url'
            ]
          })

How can I read out the callback from this request? I have tried the following in my own code:

client.deleteCache(process.env.CLOUDFLARE_ZONE, { "files": [url] }, function (data) {
    console.log(`Cloudflare cache purged for: ${url}`);
    console.log(`Callback:${data}`);
})

and:

client.deleteCache('1', {
    files: [
        'https://example.com/purge_url'
    ]
}).then(function(a,b){
    console.log('helllllllooooooooo');
})

to no avail. :(

like image 390
jo v Avatar asked Mar 04 '26 07:03

jo v


1 Answers

Purging Cloudflare cache by url:

var Cloudflare = require('cloudflare');

const { CF_EMAIL, CF_KEY, CF_ZONE } = process.env;

if (!CF_ZONE || !CF_EMAIL || !CF_KEY) {
  throw new Error('you must provide env. variables: [CF_ZONE, CF_EMAIL, CF_KEY]');
}
const client = new Cloudflare({email: CF_EMAIL, key: CF_KEY});
const targetUrl = `https://example.com/purge_url`;

client.zones.purgeCache(CF_ZONE, { "files": [targetUrl] }).then(function (data) {
  console.log(`Cloudflare cache purged for: ${targetUrl}`);
  console.log(`Callback:`, data);
}, function (error) {
  console.error(error);
});

You can lookup cloudflare zone this way:

client.zones.browse().then(function (zones) {
  console.log(zones);
})

Don't forget to install the current client version:

npm i cloudflare@^2.4.1 --save-dev
like image 85
karser Avatar answered Mar 06 '26 02:03

karser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!