// 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() + (7*24*60*60*1000)); | |
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment