Use Cloudflare Workers – example workers.js.
Code:
export default {
async fetch(request, env, ctx) {
// Get the country code from request.cf and convert it to uppercase
const country = request.cf?.country?.toUpperCase();
const Tier1Countries = ["US", "CA"];
const Tier2Countries = ["ES", "BE"];
const Tier3Countries = ["ID", "PH"];
const BlockedCountries = ["PK", "SA", "IR"];
// List of US states requiring age verification as of 2025
const ageVerificationStates = [
"LA", "UT", "MS", "VA", "AR", "TX", "MT", "NC", "ID", "KS",
"KY", "NE", "IN", "AL", "OK", "FL", "SC", "TN", "GA", "WY", "SD"
];
// If country cannot be determined, return a default response
if (!country) {
return new Response("Hello World!", { status: 200 });
}
// Block access for countries in the BlockedCountries list
if (BlockedCountries.includes(country)) {
return new Response("Access Denied", { status: 403 });
}
// Handle Tier 1 countries (US and CA)
if (Tier1Countries.includes(country)) {
if (country === "US") {
// Get the state code from request.cf and convert it to uppercase
const state = request.cf?.regionCode?.toUpperCase();
// If state cannot be determined, return a default response
if (!state) {
return new Response("Hello World!", { status: 200 });
}
// Check if the state requires age verification
if (ageVerificationStates.includes(state)) {
// Redirect to age verification page for states that require it
return Response.redirect("https://example.com/age-verify", 302);
} else {
// Redirect to standard US page for states that don’t require age verification
return Response.redirect("https://example.com/us", 302);
}
}
// Redirect non-US Tier 1 countries (e.g., CA) to a Tier 1-specific page
return Response.redirect("https://example.com/tier1", 302);
}
// Handle Tier 2 countries
if (Tier2Countries.includes(country)) {
return Response.redirect("https://example.com/tier2", 302);
}
// Handle Tier 3 countries
if (Tier3Countries.includes(country)) {
return Response.redirect("https://example.com/tier3", 302);
}
// Default response for any unhandled countries
return new Response("Hello World!", { status: 200 });
},
};