Skip to content

Instantly share code, notes, and snippets.

@saifalfalah
Last active April 4, 2021 14:55
Show Gist options
  • Save saifalfalah/3145925ca271e60f73750d42632c57e7 to your computer and use it in GitHub Desktop.
Save saifalfalah/3145925ca271e60f73750d42632c57e7 to your computer and use it in GitHub Desktop.
Detecting country using Cloudflare Workers
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
const countries = {
US: "USA",
CA: "CAN",
FR: "FRA",
DE: "DEU",
NL: "NLD",
IT: "ITA",
PT: "PRT",
IE: "IRL",
GB: "GBR",
AU: "AUS",
NZ: "NZL",
JP: "JPN",
SG: "SGP",
AE: "ARE",
CH: "CHE",
IN: "IND"
}
async function handleRequest(request) {
let countryCode;
// Sometimes cf object is not present and in that case, we default to the USA
if (!request.cf || !request.cf.country) countryCode = JSON.stringify({ country_code_iso3: "USA" });
else {
countryCode = request.cf.country;
// The app expects ISO3 country codes which exists in the `countries` object
if (countries[countryCode]) countryCode = JSON.stringify({ country_code_iso3: countries[countryCode] })
// Again, defaulting to the USA if someone is from a country that's not supported
else countryCode = JSON.stringify({ country_code_iso3: "USA" });
}
let response = new Response(countryCode, {
headers: {
"content-type": "application/json;charset=UTF-8",
"Access-Control-Allow-Origin": "*",
}
});
return response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment