Cloudflare full page caching – part 3

In part one I discussed the benefits of using Cloudflare to cache our generated HTML and in part two we set the Cloudflare Worker and got it working.  However, I’ve found that there’s one particular tweak to the example Worker which helps things run a little smoother for some setups.

I’ve talked before about WordPress cron jobs, and how it’s best to disable the default WordPress functionality and run the scheduled tasks separately, to improve performance.  However, you can’t always access the cron jobs if you’re using shared hosting, and they’re not always easy to setup even if you can access them, if you’re not very technical – for this reason I covered setting them up using an external service, such as Uptime Robot.

One advantage to setting it up this way is that you are getting the benefit of uptime monitoring for your cron job – you can set it up to get alerts if your cron jobs have stopped working.  However, the downside is that the full page caching that we’ve just setup will stop this from working!

We need to modify the “shouldBypassEdgeCache” function in our Worker, adding in the following lines…

    let url = new URL(request.url) //check for WP Cron
    let path = url.pathname
    if(path.indexOf("wp-cron.php")>0) {
      bypassCache = true;
    }
    else {

This is checking to see if the URL includes “wp-cron.php”, which is the file that runs the scheduled tasks in WordPress, and always bypasses the cache if it does.

The full “shouldBypassEdgeCache” function should now look like this…

function shouldBypassEdgeCache(request, response) {
  let bypassCache = false;

  if (request && response) {
    let url = new URL(request.url) //check for WP Cron
    let path = url.pathname
    if(path.indexOf("wp-cron.php")>0) {
      bypassCache = true;
    }
    else {
      const options = getResponseOptions(response);
      const cookieHeader = request.headers.get('cookie');
      let bypassCookies = DEFAULT_BYPASS_COOKIES;
      if (options) {
        bypassCookies = options.bypassCookies;
      }
      if (cookieHeader && cookieHeader.length && bypassCookies.length) {
        const cookies = cookieHeader.split(';');
        for (let cookie of cookies) {
          // See if the cookie starts with any of the logged-in user prefixes
          for (let prefix of bypassCookies) {
            if (cookie.trim().startsWith(prefix)) {
              bypassCache = true;
              break;
            }
          }
          if (bypassCache) {
            break;
          }
        }
      }
    }
  }

  return bypassCache;
}

I hope you’ve found this little mini-series on full page caching in WordPress useful.

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.