Cloudfare Worker Fails For Geolocating data

Hi,

I struggle with a cloudfare worker and I can’t find why it fails.

Probably a stuipid mistake.

Can anyone can help us ?

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

async function handleRequest(request) {
  // Check if request is for www.cecile-zakine.fr
  if (request.headers.get('host') !== 'www.cecile-zakine.fr') {
    return fetch(request)
  }

  // Check if a country cookie is already set
  let countryCookie = request.headers.get('Cookie')
  if (countryCookie && countryCookie.includes('country')) {
    // Get the value of the country cookie
    let countryCode = getCookie('country', countryCookie)

    // List of countries to redirect
    let countriesToRedirect = ['EN', 'RU', 'IT', 'DE']

    // Redirect to corresponding site if country is in the list
    if (countriesToRedirect.includes(countryCode)) {
      let redirectUrl = `https://www.toto.fr/${countryCode.toLowerCase()}`
      return Response.redirect(redirectUrl, 302)
    } else {
      let redirectUrl = `https://www.wyz.com/${countryCode.toLowerCase()}`
      return Response.redirect(redirectUrl, 302)
    }
  }

  // Get country code from Cloudflare
  let cfResponse = await fetch('https://cloudflare-dns.com/dns-query?name=whoami.cloudflare&type=TXT', {
    headers: {
      'accept': 'application/dns-json',
    },
  })
  let cfData = await cfResponse.json()
  let countryCode = cfData.Answer[0].data.replace('"', '').replace('"', '')

  // Set country cookie
  let setCookieHeader = `country=${countryCode}; path=/;`
  let response = new Response(null, {
    headers: {
      'Set-Cookie': setCookieHeader,
    },
  })

  // Fetch original response
  let originalResponse = await fetch(request)

  // Make sure we only modify text, not images.
  let type = originalResponse.headers.get('Content-Type') || ''
  if (!type.startsWith('text/html')) {
    // Not text/html. Don't modify.
    return originalResponse
  }

  // Copy original response into the new response object
  response = new Response(originalResponse.body, originalResponse)

  // Set location data as cookies
  const geo_properties = [
    'asn',
    'asOrganization',
    'colo',
    'country',
    'isEUCountry',
    'city',
    'continent',
    'latitude',
    'longitude',
    'metroCode',
    'postalCode',
    'region',
    'regionCode',
    'timezone',
  ];

  const domain = request.headers.get('host')
  geo_properties.forEach(property => {
    let cookie_value = request.cf[property]
    if (cookie_value) {
      // Build the cookie string and append to response
      let a_cookie = `cp_${property}=${cookie_value}; path=/; domain=${domain}; secure; SameSite=None`
      response.headers.append('Set-Cookie', a_cookie)
    }
  })

  // Add support for ESI
  response.headers.set('Content-Type', 'text/html; charset=UTF-8')
  response.headers.set('X-Content-Type-Options', 'nosniff')
  response.headers.set('Surrogate-Control', 'ESI/1.0')
  response.headers.set('Cache-Control', 'no-store')

  // Use ESI to include dynamic content
  response = new HTMLRewriter()
    .on('esi-include', new ESIIncludeHandler())
    .transform

We suggest checking in the developers discord.

Developers Discord

This is the best place to debug workers.