Skip to content

Instantly share code, notes, and snippets.

@adamcrampton
Created April 1, 2019 05:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save adamcrampton/db01c1bdef53d22ac8ea20eadae4c133 to your computer and use it in GitHub Desktop.
Save adamcrampton/db01c1bdef53d22ac8ea20eadae4c133 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