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.
Example:
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’)
if (VISITOR_COUNTRY == ‘US’) {
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) {
element.setAttribute(
this.attributeName,
attribute.replace(OLD_URL, NEW_URL),
)
}
}
}
const rewriter = new HTMLRewriter()
.on(‘img’, new AttributeRewriter(‘src’))
addEventListener(‘fetch’, event => {
event.respondWith(handleRequest(event.request))
})
However, I’m getting 522 Origin Connection Time-out when testing it on the worker domain. Any help is appreciated.