David Ellwood
David Ellwood

Reputation: 1

Cloudflare Worker template script error - country redirect

I grabbed example script from the Cloudflare GitHub worker example page for a simple country redirect. It fails and I don't know why? (I am not particularly strong in code stuff).

Error is:

Script modified; context reset. worker.js:17 Uncaught TypeError: Cannot read properties of undefined (reading 'country')
    at redirect (worker.js:17)
    at worker.js:28 redirect @ worker.js:17 (anonymous) @ worker.js:28 Uncaught (in response) TypeError: Cannot read properties of undefined (reading 'country')

The template code is:

/**
 * A map of the URLs to redirect to
 * @param {Object} countryMap
 */
const countryMap = {
  US: "https://example.com/us",
  EU: "https://eu.example.com/",
}

/**
 * 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))
})

From

https://github.com/cloudflare/cloudflare-docs/blob/production/products/workers/src/content/examples/country-code-redirect.md

Does anyone have advice on this? This is being run on the Cloudflare Workers system.

Upvotes: 0

Views: 801

Answers (1)

Kenton Varda
Kenton Varda

Reputation: 45151

This is a known problem with the Worokers preview. request.cf is always undefined when using the embedded preview next to the editor. If you use wrangler dev to test your code instead, it will work correctly there, and it will also work once deployed.

Upvotes: 1

Related Questions