URL rewrite based on visitor country code

I’m writing a worker to change the image src attribute based on the visitor country. It would rewrite the URL to the CDN domain for that specific country.


US => us.cdn
EU => eu.cdn

Here is what I had

const OLD_URL = ‘gl.cdn’
let NEW_URL = 'gl.cdn

async function handleRequest(request) {
const VISITOR_COUNTRY = request.headers.get(‘cf-ipcountry’)
NEW_URL = ‘us.cdn.com
const result = await fetch(request)
return rewriter.transform(result)

class AttributeRewriter {
constructor(attributeName) {
this.attributeName = attributeName
element(element) {
const attribute = element.getAttribute(this.attributeName)
if (attribute) {
attribute.replace(OLD_URL, NEW_URL),

const rewriter = new HTMLRewriter()
.on(‘img’, new AttributeRewriter(‘src’))

addEventListener(‘fetch’, event => {

However, I’m getting 522 Origin Connection Time-out when testing it on the worker domain. Any help is appreciated.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.