From 8a00a3fdd3db45eab4073cced78900ee45247113 Mon Sep 17 00:00:00 2001 From: Chris Amico Date: Tue, 9 Jan 2024 10:48:39 -0500 Subject: [PATCH] Add a plugin to bust cache on deploy --- .gitignore | 1 + netlify.toml | 3 +++ plugins/cache-bust/index.js | 30 ++++++++++++++++++++++++++++++ plugins/cache-bust/manifest.yml | 3 +++ utility/purge.sh | 7 +++++++ 5 files changed, 44 insertions(+) create mode 100644 netlify.toml create mode 100644 plugins/cache-bust/index.js create mode 100644 plugins/cache-bust/manifest.yml create mode 100755 utility/purge.sh diff --git a/.gitignore b/.gitignore index e3fc1919a..db643eacd 100644 --- a/.gitignore +++ b/.gitignore @@ -27,6 +27,7 @@ public/assets/ .netlify # Local test env file +.env.secret .env.test .env.sentry-build-plugin playwright-report diff --git a/netlify.toml b/netlify.toml new file mode 100644 index 000000000..c6bf7b264 --- /dev/null +++ b/netlify.toml @@ -0,0 +1,3 @@ + +[[context.production.plugins]] +package = "/plugins/cache-bust" diff --git a/plugins/cache-bust/index.js b/plugins/cache-bust/index.js new file mode 100644 index 000000000..7d336706a --- /dev/null +++ b/plugins/cache-bust/index.js @@ -0,0 +1,30 @@ +// bust cache after a production deploy succeeds + +const { CLOUDFLARE_ID, CLOUDFLARE_TOKEN } = process.env; +const PURGE_URL = `https://api.cloudflare.com/client/v4 +/zones/${CLOUDFLARE_ID}/purge_cache`; + +export async function onSuccess() { + if (!CLOUDFLARE_ID) { + console.error("CLOUDFLARE_ID is not set."); + return; + } + + const resp = await fetch(PURGE_URL, { + method: "POST", + headers: { + authorization: `Bearer ${CLOUDFLARE_TOKEN}`, + "content-type": "application/json", + }, + body: JSON.stringify({ purge_everything: true }), + }); + + if (!resp.ok) { + console.error("Error purging cache."); + console.error(`${resp.status}: ${resp.statusText}`); + } + + const result = await resp.json(); + + console.log(JSON.stringify(result, null, 2)); +} diff --git a/plugins/cache-bust/manifest.yml b/plugins/cache-bust/manifest.yml new file mode 100644 index 000000000..07559c2c0 --- /dev/null +++ b/plugins/cache-bust/manifest.yml @@ -0,0 +1,3 @@ +# cache bust plugin + +name: cache-bust diff --git a/utility/purge.sh b/utility/purge.sh new file mode 100755 index 000000000..1098561a8 --- /dev/null +++ b/utility/purge.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env sh + +curl --request POST \ + --url "https://api.cloudflare.com/client/v4/zones/${CLOUDFLARE_ID}/purge_cache" \ + --header 'Content-Type: application/json' \ + --header "Authorization: Bearer ${CLOUDFLARE_TOKEN}" \ + --data '{"purge_everything": true}'