Hi!
The following worker sets a cookie with the contents of the cf-ipcountry header.
For example “DK” for Denmark. I’ve deployed it unto 5 routes (5 cloudflare domains).
Only 2 of the 5 gets the cookie set. I’ve been in contact with Cloudflare Support, and they assure me that the worker is run for the 5 routes, and that it seems to be the code.
The full code is below. It works for my two “.dk” domains, but not for the two “.com” domains nor the “.et” domain. All of them are on the pro-plan and have, as far as i can tell, the same cloudflare settings and all traffic is proxied through cloudflare.
Can you spot the error?
// 1. Register a FetchEvent listener that sends a custom
// response for the given request.
addEventListener(‘fetch’, event => {
event.respondWith(handleRequest(event.request))
})
// 2. Return a custom request object
async function handleRequest(request) {
// Forward request to origin, get response.
let response = await fetch(request);
// Copy Response object so that we can edit headers.
response = new Response(response.body, response);
const country = request.headers.get(‘cf-ipcountry’);
let expiryDate = new Date();
expiryDate.setTime(expiryDate.getTime() + (72460601000));
let expires = expiryDate.toUTCString();
const countryCookie = universal_visitor_country=${country}; Expires=${expires}; Path=/; HttpOnly; SameSite=Lax; Secure
;
// Set cookie so that we don’t add the headers
// next time.
response.headers.append(‘Set-Cookie’, countryCookie);
// Return on to client.
return response;
}