Skip to content

Commit

Permalink
clear cache with cloudflare worker
Browse files Browse the repository at this point in the history
  • Loading branch information
GraemeFulton committed Jun 20, 2024
1 parent 6a1134b commit 94130b6
Showing 1 changed file with 42 additions and 22 deletions.
64 changes: 42 additions & 22 deletions lib/utils/cloudflare.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,44 @@
import axios from 'axios'
export const purgeCloudFlareCache = async(url) =>{
try {
const response = await axios.post(
`https://api.cloudflare.com/client/v4/zones/${process.env.CLOUDFLARE_API_ZONE}/purge_cache`,
{ files: [`${process.env.NEXT_PUBLIC_HOME_URL}${url}`] },
{
headers: {
'Authorization': `Bearer ${process.env.CLOUDFLARE_API_TOKEN}`,
'Content-Type': 'application/json'
}
}
);

if (response.data.success) {
return true
// res.status(200).json({ message: 'Cache purged successfully' });
} else {
console.log('Cloudflare cache purge failed', response.data)
import axios from "axios";
export const purgeCloudFlareCache = async url => {
try {
const response = await axios.post(
`https://api.cloudflare.com/client/v4/zones/${process.env.CLOUDFLARE_API_ZONE}/purge_cache`,
{ files: [`${process.env.NEXT_PUBLIC_HOME_URL}${url}`] },
{
headers: {
Authorization: `Bearer ${process.env.CLOUDFLARE_API_TOKEN}`,
"Content-Type": "application/json",
},
}
} catch (error) {
console.log('Cloudflare cache purge failed', error)
);

if (response.data.success) {
return true;
// res.status(200).json({ message: 'Cache purged successfully' });
} else {
console.log("Cloudflare cache purge failed", response.data);
}
}
clearWorkerCache(url);
} catch (error) {
console.log("Cloudflare cache purge failed", error);
}
};

const clearWorkerCache = async path => {
const workerURL = `${process.env.NEXT_PUBLIC_HOME_URL}/clear-cache?path=${encodeURIComponent(path)}`;

try {
const response = await fetch(workerURL, {
method: "GET",
});

if (!response.ok) {
throw new Error("Failed to clear cache");
}

const result = await response.text();
res.status(200).json({ message: result });
} catch (error) {
res.status(500).json({ error: error.message });
}
};

0 comments on commit 94130b6

Please sign in to comment.