Block Countries

This script demonstrates how to block requests coming from specific countries using the x-sp-client-geo-countrycode request header variable. See this page for more details on available request header variables.

addEventListener("fetch", event => {
  event.respondWith(handleRequest(event.request));
});

// Block requests from the United States and Canada
const blockedCountries = ["US", "CA"];

async function handleRequest(request) {
  // Get country code of request from header variable
  const requestCountryCode = request.headers.get("x-sp-client-geo-countrycode");

  // Check if the country code should be blocked and return a 403 if so
  if (blockedCountries.includes(requestCountryCode)) {
    return new Response("Sorry, this page is not available.", {
      status: 403,
      statusText: "Forbidden"
    });
  }

  // Pass request through if from a different country
  return fetch(request);
}

What’s Next