Issue with cloudflare workers country based redirection


#1

Hi,

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 => {
  event.respondWith(fetchAndApply(event.request))
})

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
  console.log(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


#2

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).


#3

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