Cloudflare Workers Refresh Page Spam

Hey
I am using Cloudflare as a reverse proxy. It works well but when someone spam STRG + R (refresh page) the worker loads them (and when I show a website it can cause 30 requests because of 30 files)

Is there a way to prevent that?

Best regards

Assign a global variable and use the rayID as key, then accumulate that for every request. When the global reaches a specific value, then use the Cloudflare API to add them to the firewall.

Afaik, that’s the only way.

3 Likes

As thomas4 said using the rayID is the only way, but instead of assigning a global variable I would use the rayID as the cacheKey for your request to the origin server.

const {url, headers} = request
const rayID = headers.get('cf-ray')
const cacheInSeconds = 60


const response = await fetch(url, {
	cf: {
		cacheTtlBystatus: {
			'200-299': cacheInSeconds, 
			404: 1, 
			'500-599': 0 
		},
		cacheEverything: true,
		cacheKey: rayID
	}
})
3 Likes

While caching to prevent origin-load is a great idea, you’d still be billed for worker requests.

By using the firewall, the requests won’t reach the worker at all.

3 Likes

Are we storing something in the KV? Would be interested to see a code sample if you have any.

https://community.cloudflare.com/t/workers-global-variables

Never rely on globals on workers though, there are very few use-cases.

Eh, CF-Ray seems to change on every request. Am I missing something here?

It doesn’t change as long as the cookies are kept, you can see it working in the browser sample.

Also, that example only uses globals, it doesn’t rely on rayIDs.

CF is working on removing cookies entirely, so using rayIDs will probably work a little bit more reliably then (Or the opposite, who knows). Anyway, it’s not reliable and don’t have many use-cases, like I said.

Just checked that my Workers endpoints are not setting any cookies.

Anyways, I will try to figure out something with connecting IPs. Got some bad dudes trenching on my endpoints.