Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fmt/7eae1d4df0e0f46ed65f4d681298a417 to your computer and use it in GitHub Desktop.
Save fmt/7eae1d4df0e0f46ed65f4d681298a417 to your computer and use it in GitHub Desktop.
For use with Cloudflare Worker - detects region and sets a cookie
// For use with a Cloudflare Worker
addEventListener('fetch', event => {
event.respondWith(fetchAndApply(event.request));
});
async function fetchAndApply(request) {
// Only run if cookie not present.
let cookies = request.headers.get('Cookie') || "";
if (cookies.includes("aam=true")) {
console.log("AAM not set")
return fetch(request);
}
// Set country and cookie value
let country = request.headers.get('cf-ipcountry');
const aamValue = (country === "AU") ? "aam=true" : "aam=false";
// Set cookie and return response
let response = await fetch(request);
// Make the headers mutable by re-constructing the Response.
response = new Response(response.body, response);
response.headers.set('Set-Cookie', aamValue);
console.log('AAM set');
return response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment