Conditional Response
This example returns a response based on the URL of the incoming request, HTTP method, User Agent, IP address, or country of origin of the request.
addEventListener("fetch", (event) => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
const BLOCKED_HOSTNAMES = ["nope.mywebsite.com", "bye.website.com"];
// Return a new Response based on a URL's hostname
const url = new URL(request.url);
if (BLOCKED_HOSTNAMES.includes(url.hostname)) {
return new Response("Blocked Host", { status: 403 });
}
// Block paths ending in .doc or .xml based on the URL's file extension
const forbiddenExtRegExp = new RegExp(/\.(doc|xml)$/);
if (forbiddenExtRegExp.test(url.pathname)) {
return new Response("Blocked Extension", { status: 403 });
}
// On HTTP method
if (request.method === "POST") {
return new Response("Response for POST");
}
// On User Agent
const userAgent = request.headers.get("User-Agent") || "";
if (userAgent.includes("bot")) {
return new Response("Block User Agent containing bot", { status: 403 });
}
// On Client's IP address
const clientIP = request.headers.get("X-Real-IP");
if (clientIP === "1.2.3.4") {
return new Response("Block the IP 1.2.3.4", { status: 403 });
}
// On Country
const country = request.headers.get("X-Country-Code");
if (country === "CN") {
return new Response("Block Request from China", { status: 403 });
}
console.error(
"Getting Client's IP address, device type, and ASN are not supported in playground. Must test on a live worker"
);
return fetch(request);
}