Using Country code to display or not item on html

Hello, I’m using the countrycode redirect, based on this example: https://developers.cloudflare.com/workers/examples/country-code-redirect

all works, but I need also to modify the workers to change the visibility of some parts of the website.

in html I have this:
<h1 id=pricetag class="label">one gazillion dollars</h1>

I need to hide when the visitors came from a specific country, instead of doing the redirect.

code of workers:

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

/**
 * Returns a redirect determined by the country code
 * @param {Request} request
 */
async function redirect(request) {
  // Use the cf object to obtain the country of the request
  // more on the cf object: 
  const country = request.cf.country

  if (country != null && country in countryMap) {
    const url = countryMap[country]
    return Response.redirect(url)
  }
  else {
    return await fetch(request)
  }
}
/**
 * A map of the URLs to redirect to
 * @param {Object} countryMap
 */
const countryMap = {
  EU: "https://baltaco.com/",
  DE: "https://silcomnorth.com/",
}

async function handleRequest(request) {
  return redirect(request)
}

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

Some suggestion?

thanks

Hi, if you need to hide the content for some specific countries I can suggest you need to follow 2 steps:

  1. create a new object of forbidden countries similar to countryMap
  2. add a new conditional statement to return a Response object

const forbidenCountryMap = {
  RU: "https://example1.com/",
  CN: "https://example2.com/",
}

//add the conditional statement

else if(country != null && country in forbidenCountryMap )
{
   const txt = 'forbiden country'
   return new Response(txt, {status: 403, statusText: txt})
}

thanks for the tip, but I was thinking of a different solution.

I thought of using the “request.cf.country” in the workers, which creates a variable, and in the script on the page I use that variable to show or not the content.

what do you think about it?

Sorry, using the key-value object wasn´t the proper approach. I should have advised using an array together with the includes method:

const forbidenCountryArr = ['RU', 'CN'];

else if(country != null && forbidenCountryArr.includes(country))
{
   const txt = 'forbiden country'
   return new Response(txt, {status: 403, statusText: txt})
}

Note that when using the Workers, you should always return a Response object or a fetch promise that resolves to and Response.

thanks for explication… I will do some more test next week, I will keep you informed.