Issue with cloudflare workers country based redirection


Im new to Cloudflare workers and writing script to redirect my website based on country id. The below script throws too many redirection error.

addEventListener('fetch', event => {

async function fetchAndApply(request) {
  let url = new URL(request.url)
  let store = ''
  //Get country code
  let country = request.headers.get('CF-IpCountry')
  if (country == 'CN') {
	store = '/stores/store/switch?___store=chinese'
  } else if (country == 'JP') {
	store = 'stores/store/switch?___store=japanese'
  } else {
	store = 'stores/store/switch?___store=default'
  store = request.url + store
  return fetch(store, request)

I have also tried below method. Its also throwing too many redirection.

return Response.redirect(store)

What im doing wrong here?

FYI: Im using magento 2.x website

In the fetch you are not using the new URL, you need to change it (the variable you are using for the if should work fine) and then request it (or redirect the user to it).

This topic was automatically closed after 14 days. New replies are no longer allowed.