proxying peasy Analytics through Cloudflare Workers

some ad blockers prevent requests to third-party domains, potentially hindering script loading and tracking. to prevent this, you can proxy the script and its requests through your own first-party domain.

you can set up a proxy with Cloudflare Workers. a free Cloudflare account is all you need to get started.

here's a guide to setting it up:

creating the Worker

create a free account at Cloudflare and navigate to Workers & Pages. create and deploy a new worker using the Hello World template. after deploying, click Edit code, remove the example code and paste the following code snippet:

Copy the following code into the editor, replace yourdomain.com with your domain, and click Deploy when finished.

export default {
	async fetch(request) {
		return await handleRequest(request);
	}
};
async function handleRequest(request) {
	const url = new URL(request.url);

	if (url.pathname === '/peasy.js') {
		return Response.redirect('https://cdn.peasy.so/peasy.js', 301);
	}

	const newUrl = new URL(`https://api.peasy.so${url.pathname}`);
	newUrl.search = url.search;

	const newRequest = new Request(newUrl, {
		method: request.method,
		headers: request.headers,
		body: request.body
	});

	newRequest.headers.set('X-Peasy-IP', request.headers.get('CF-Connecting-IP'));

	newRequest.headers.set('X-Peasy-Country', request.headers.get('CF-IPCountry'));
	newRequest.headers.set('X-Peasy-City', request.headers.get('CF-IPCity'));

	return fetch(newRequest);
}

creating a worker route

now navigate to to Workers Routes, and create a new route there.

Set the Route to match the domain you just configured in the Worker code. In our case, it's sln.yourdomain.com/_. Then, select the Worker you previously created, and hit Save. Don't forget the _ wildcard.

adding the dns record

for the last bit on Cloudflare, create a DNS record with type A, name it peasy, and set the content to 192.0.2.1. this is a dummy IP address that will be replaced by Cloudflare with the Worker's IP address.

this should make sure all traffic sent to peasy.yourdomain.com is proxied through the Worker.

updating the script

finally, update the script tag on your website to point to the new domain:

<script src="https://peasy.yourdomain.com/peasy.js" data-website-id="<website_id>" async></script>

that's it! you've successfully set up a proxy for peasy Analytics through Cloudflare Workers. now you can track your users without worrying about ad blockers blocking the script.

try web analytics
you'll actually love.

sign up for peasy today. free to start and while below 3000 events per month, then $9 monthly.