Cloudflare js worker allow list of countries and block the rest

#1

i’m trying to adjust the following code to be like allow if the country in the list and block if not , the current code does the oppiste block if the country in the list and allow if not

any tips here i’m not that good in js ?

addEventListener('fetch', event => {
  event.respondWith(blockCountries(event.request))
})

//Add countries to this Set to block them
const countries = new Set([  
  "US", // United States
  "SG", // Singapore 
  "BR"  // Brazil
])

async function blockCountries(request) {
  // Get country value from request headers
  let country = request.headers.get('cf-ipcountry')

  // Find out if country is on the block list
  let countryBlocked = countries.has(country)

  // If it's on the blocked list, give back a 403
  if (countryBlocked){
    return new Response("This page not available in your country",
        { status: 403, statusText: "Forbidden" })
  }

  // Catch-all return of the original response
  return await fetch(request)
}
#2

Is there a particular reason you’d like to do this via a worker?

#3

yeah , i’ve some VOD with geo location restriction due copy rights , so i’ve to play it in MENA regain only , i’ve to set URLs for that vods in the rule , that why

#4

And you cant do this with firewall rules?

#5

i need to through custom error msg on the jwplayer can i do this via firewall rules ?

#6

You could customise the overall message, but not specifically for one firewall rule. In that case a worker might be the better choice.

#7

yeah i believe so ,

#8

This should work:

addEventListener('fetch', event => {
  event.respondWith(blockCountries(event.request))
})

//Add countries to this Set to Allow them
const countries = new Set([  
  "US", // United States
  "SG", // Singapore 
  "BR"  // Brazil
])

async function blockCountries(request) {
  // Get country value from request headers
  let country = request.headers.get('cf-ipcountry')

  // Find out if country is on the allow list
  let countryAllowed = countries.has(country)

  // If it's on the allow list, give back a 403
  if (countryAllowed){
    // Catch-all return of the original response
    return await fetch(request)
    
  }
  return new Response("This page not available in your country",
        { status: 403, statusText: "Forbidden" })
}