You can use Cloudflare Workers to proxy your Beam Analytics requests. Set up a Cloudflare account and get up to 100,000 requests per day with Cloudflare Workers. Here’s how to create a proxy.
Step 1: Create a worker
To start configuring your proxy, in your Cloudflare account:
Step 2: Quick edit the worker
Click on the 'Quick edit' where you can edit the code for your worker:
The following screen will appear:
Remove the default code that Cloudflare presents on the left side of the screen and paste the code that we present below instead.
const ScriptName = '/js/script.js';
const Endpoint = '/api/log';
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 })
}
async function getScript(event, extensions) {
let response = await caches.default.match(event.request);
if (!response) {
response = await fetch("https://beamanalytics.b-cdn.net/beam.min.js");
event.waitUntil(caches.default.put(event.request, response.clone()));
}
return response;
}
async function postData(event) {
const request = new Request(event.request);
request.headers.delete('cookie');
return await fetch("https://api.beamanalytics.io/api/log", request);
}
Important
We recommend you change the folder name in the first two lines in the code above. This makes your proxy more difficult to discover and block.
Step 3: Test the script
Your Beam script should be accessible at the following URL:
https://worker-name.cloudflare-username.workers.dev/folder-name/script.js
where the things you need to change are:
You should see some JavaScript code when you load this URL. This URL is the proxied snippet that you’ll use in step 4.
Step 4: Integrate a new snippet into your site header
You can now use the proxied snippet from step 3 to replace the Beam Analytics script in the of your site.
The new snippet should look like
<script
defer
data-token="your-token"
data-api="https://worker-name.cloudflare-username.workers.dev/folder-name/log"
src="https://worker-name.cloudflare-username.workers.dev/folder-name/script.js"
></script>
where the things you need to change are:
You’re done! You're now counting your website stats using a proxy.