From e4dc62d3d191bbe71599d4992828a7309ff2412f Mon Sep 17 00:00:00 2001 From: Rocco <17133963+rocco-haro@users.noreply.github.com> Date: Tue, 17 Oct 2023 19:13:24 -0700 Subject: [PATCH] Update cloudflare.md Cloudflare Workers now require the Module Workers format. I've tested this code snippet & confirmed it works. --- docs/proxy/guides/cloudflare.md | 50 ++++++++++++++++----------------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/docs/proxy/guides/cloudflare.md b/docs/proxy/guides/cloudflare.md index 14533238..8edf9998 100644 --- a/docs/proxy/guides/cloudflare.md +++ b/docs/proxy/guides/cloudflare.md @@ -35,39 +35,39 @@ Do avoid words like 'plausible', 'analytics', 'tracking', 'stats', etc. as they const ScriptName = '/js/script.js'; const Endpoint = '/api/event'; -const ScriptWithoutExtension = ScriptName.replace('.js', '') - -addEventListener('fetch', event => { - event.passThroughOnException(); - event.respondWith(handleRequest(event)); -}) - -async function handleRequest(event) { - const pathname = new URL(event.request.url).pathname - const [baseUri, ...extensions] = pathname.split('.') - - if (baseUri.endsWith(ScriptWithoutExtension)) { - return getScript(event, extensions) - } else if (pathname.endsWith(Endpoint)) { - return postData(event) - } - return new Response(null, { status: 404 }) -} +const ScriptWithoutExtension = ScriptName.replace('.js', ''); + +export default { + async fetch(request, env, ctx) { + const pathname = new URL(request.url).pathname; + const [baseUri, ...extensions] = pathname.split('.'); -async function getScript(event, extensions) { - let response = await caches.default.match(event.request); + if (baseUri.endsWith(ScriptWithoutExtension)) { + return await getScript(request, extensions); + } else if (pathname.endsWith(Endpoint)) { + return await postData(request); + } + return new Response(null, { status: 404 }); + }, +}; + +async function getScript(request, extensions) { + let response = await caches.default.match(request); if (!response) { response = await fetch("https://plausible.io/js/plausible." + extensions.join(".")); - event.waitUntil(caches.default.put(event.request, response.clone())); + const cachePut = caches.default.put(request, response.clone()); + // Wait for the cache operation to complete before proceeding + await cachePut; } return response; } -async function postData(event) { - const request = new Request(event.request); - request.headers.delete('cookie'); - return await fetch("https://plausible.io/api/event", request); +async function postData(request) { + const newRequest = new Request(request); + newRequest.headers.delete('cookie'); + return await fetch("https://plausible.io/api/event", newRequest); } + ``` Once you've added the above code to the worker, you can click on the 'Save and Deploy' button on the top right. On the confirmation message, do confirm that you want to save and deploy your worker by clicking on the 'Save and Deploy' button again.