I have not tested it via workers apparently.
I have tested it against a normal URL on my Server.
Logged in at GTmetrix:
Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.193 Safari/537.36 GTmetrix
Anonym GTmetrix:
Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.193 Safari/537.36 GTmetrix
It definitely shows up with the “Gtmetrix” in my logs (serverside). But I actually dont know how to detect it via Workers, or why it does not show up there. Maybe it gets cut off there?
But you’re right. When I check what GTmetrix shows me as “request Header” it is not part of the user-agent:
On my server it shows up anyway as I catch the raw header and save it to a DB
As the syntax is:
User-Agent: <product> / <product-version> <comment>
(Source: https://www.geeksforgeeks.org/http-headers-user-agent/)
Maybe the comment is “GTmetrix” and is getting cut of by CloudFlare? I cant tell sorry. Maybe the OP should create a ticket to ask CloudFlares support if there is a way to detect/fetch the raw full user-agent?
But the approach of the OP seems to be right. As this example uses the same method:
const userAgent = request.headers.get("User-Agent") || ""
if (userAgent.includes("bot")) {
return new Response("Block User Agent containing bot", { status: 403 })
}