I have a cloudflare worker that will insert custom CSS into the page if the country is not U.S/Canada. This works perfectly, however - it will break all redirects when the CSS is inserted. Attached below is the worker scripts
addEventListener('fetch', event => {
event.passThroughOnException()
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const country = request.cf.country
if (country != 'US' && country !='CA') {
const response = await fetch(request)
const type = response.headers.get("Content-Type") || "";
if (!type.startsWith("text/html")) {
return response;
}
var html = await response.text()
// Inject scripts
const customScripts = 'styling here'
html = html.replace( /<\/body>/ , customScripts)
// return modified response
return new Response(html, {
headers: response.headers
})
}
}
The redirects are broken because they use a special HTTP status code (usually 301 or 302), but your Worker code is not copying the status code over to the final response, so the final response ends up always having a 200 status code.
Try changing this:
To this:
This way, the new response copies over all of the properties of the old response, except for the body. This includes the
status
property, so the status code will be copied over.By the way, unrelated to this problem, I notice another issue with your code:
It looks like if this condition evaluates to false (that is, if
country
is either'US'
or'CA'
), then yourhandleRequest()
function doesn't return a response at all. In this case, an exception will be thrown, and the client will see an 1101 error page. I recommend adding anelse
clause that returns the response that you want users in the US and Canada to see.