loading
Automatically purge Cloudflare cache after Netlify build

Automatically purge Cloudflare cache after Netlify build

keep them in phase

Although Netlify provides CDN service, Cloudflare has more edge locations around the world. What’s more, Netlify hosted sites are hardly reached in China, while Cloudflare still lives. With this in mind, I decided to switch to Cloudflare for load balancing.

However, pushing post/file changes to Netlify did not clear Cloudflare’s cache, that’s a mess. So, I’m going to use Cloudflare’s API together with Netlify’s outgoing webhook to make the cache in the same pace.

Cloudflare API

In Cloudflare’s API document, we cloud find a service named Purge All Files, which remove ALL files from Cloudflare’s cache. Other APIs like Purge Files by Cache-Tags or Host, only applies to Cloudflare’s enterprise users.

Using this API, we need to POST to its API endpoint: POST zones/:identifier/purge_cache. For example, using cURL:

curl -X POST "https://api.cloudflare.com/client/v4/zones/023e105f4ecef8ad9ca31a8372d0c353/purge_cache" \
     -H "X-Auth-Email: [email protected]" \
     -H "Authorization: Bearer c2547eb745079dac9320b638f5e225cf483cc5cfdda41" \
     -H "Content-Type: application/json" \
     --data '{"purge_everything":true}'

The required parameters are:

  • :identifier: this is the unique ID for your domain, find it in Cloudflare dash
  • X-Auth-Email: this is the email address you use to log in to your Cloudflare account
  • Authorization: this is the API token that can be generated on the Cloudflare API Tokens page

Purge Cloudflare cache with a serverless function

Now we can create a serverless function to purge Cloudflare’s cache. Here, I’m going to use Netlify Functions for this purpose.

Just create a new function in Netlify:

"use strict";
const axios = require("axios");

exports.handler = (event, context, callback) => {

    const headers = {
        "X-Auth-Email": `${process.env.CF_EMAIL}`,
        "Authorization": `Bearer ${process.env.CF_PURGE_KEY}`,
        "Content-Type": "application/json"
    }

    const callbackHeaders = {
        "Content-Type": "application/vnd.api+json; charset=utf=8"
    };

    let url = `https://api.cloudflare.com/client/v4/zones/${process.env.CF_ZONE_ID}/purge_cache`;
    let data = '{ "purge_everything": true }';

    if (event.headers["x-netlify-event"]) {
        axios.post(url, data, {
                headers: headers
            })
            .then((res) => {
                callback(null, {
                    statusCode: 200,
                    headers: callbackHeaders,
                    body: JSON.stringify(res.data),
                });
            })
            .catch((err) => {
                callback(null, {
                    statusCode: 500,
                    headers: callbackHeaders,
                    body: JSON.stringify(err.message),
                });
            });
    }
}

Don’t forget to set the corresponding Environment variables in Netlify’s web interface.

Set up Netlify to trigger the cache purge

Now that you have the serverless function set up, the next step is to instruct Netlify to trigger the function after a successful deployment. To do this, navigate to your Netlify’s settings, and click the Build & Deploy tab.

Next, scroll down to the bottom of the page to the Deploy Notifications section. Click on the Add Notification dropdown, and select Outgoing Webhook. Use the following settings to instruct Netlify to trigger your Cloudflare cache purge function after a successful deployment.

Netlify webhook settings

Set the URL to notify to the Netlify Function’s endpoint that you just created.

In the future, it’d be nice to secure the configuration with a JWT token. For now, this setup works fine just as I needed.

林宏

Frank Lin

Hey, there! This is Frank Lin (@flinhong), one of the 1.4 billion 🇨🇳. This 'inDev. Journal' site holds the exploration of my quirky thoughts and random adventures through life. Hope you enjoy reading and perusing my posts.

YOU MAY ALSO LIKE

Setup an IKEv2 server with StrongSwan

Tutorials

2020.01.09

Setup an IKEv2 server with StrongSwan

IKEv2, or Internet Key Exchange v2, is a protocol that allows for direct IPSec tunneling between the server and client. In IKEv2 implementations, IPSec provides encryption for the network traffic. IKEv2 is natively supported on some platforms (OS X 10.11+, iOS 9.1+, and Windows 10) with no additional applications necessary, and it handles client hiccups quite smoothly.

Practising closures in JavaScript

JavaScript Notes

2018.12.17

Practising closures in JavaScript

JavaScript is a very function-oriented language. As we know, functions are first class objects and can be easily assigned to variables, passed as arguments, returned from another function invocation, or stored into data structures. A function can access variable outside of it. But what happens when an outer variable changes? Does a function get the most recent value or the one that existed when the function was created? Also, what happens when a function invoked in another place - does it get access to the outer variables of the new place?

Using Liquid in Jekyll - Live with Demos

Web Notes

2016.08.20

Using Liquid in Jekyll - Live with Demos

Liquid is a simple templating language that Jekyll uses to process pages on your site. With Liquid you can output an modify variables, have logic statements inside your pages and loop over content.

TOC