Workers - Country code redirect

Even i have created the worker code and done everything as described my country code redirection is not working properly. Could you please help me on this?
My website is : venusshoes.com and my code is ;
/**

if (country != null && country in countryMap) {
const url = countryMap[country]
return Response.redirect(url)
} else {
return fetch(request)
}
}

addEventListener(“fetch”, event => {
event.respondWith(redirect(event.request))
})

Unfortunately the code is a bit unreadable because there’s no formatting and Discourse automatically converted your links.
Can you edit your post to format the code?

Put 3 backticks (```) above and under your code like this

1 Like

/**
 * A map of the URLs to redirect to
 * @param {Object} countryMap
 */
const countryMap = {
  US: 'https://venusshoes.com/en',
  TR: 'https://venusshoes.com/tr',
  FR: 'https://venusshoes.com/fr',
  DE: 'https://venusshoes.com/de',
  RU: 'https://venusshoes.com/ru',
  ES: 'https://venusshoes.com/es',
  AT: 'https://venusshoes.com/de',
  IT: 'https://venusshoes.com/en',
  UK: 'https://venusshoes.com/en',
  PT: 'https://venusshoes.com/pt',
}
/**
 * Returns a redirect determined by the country code
 * @param {Request} request
 */
function redirect(request) {
  // Use the cf object to obtain the country of the request
  // more on the cf object: https://developers.cloudflare.com/workers/runtime-apis/request#incomingrequestcfproperties
  const country = request.cf.country

  if (country != null && country in countryMap) {
    const url = countryMap[country]
    return Response.redirect(url)
  } else {
    return fetch(request)
  }
}

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

hi did you have any time to check the code? i have rewrite the code as you explained

Thanks in advance

Hey,

Apologies for missing your reply notification.
Thanks for re-formatting your code, that definitely helps :slightly_smiling_face:
I’ll take a look at your code later today and see if I can find any issue with it.

By the way, what did you mean exactly with the following?

my country code redirection is not working properly.

Is it always redirecting to a specific URL no matter what country you’re visiting from or is it giving some kind of error?

Yes exactly. It always redirecting to “https://venusshoes.com/” no matter what country i am visiting from.

But if user visit the website from US . it redirects to Venus Shoes | Venüs as expected. But

I have been unable to reproduce the issue you’re seeing. I re-deployed it to double-check, but everything seems fine to me.

it seems like you forgot to finish your sentence there(?)