Skip to content

Instantly share code, notes, and snippets.

@dogweather
Last active December 1, 2023 15:52
Show Gist options
  • Save dogweather/051f0743de9d941bb1a0b8a8a7f8f6ff to your computer and use it in GitHub Desktop.
Save dogweather/051f0743de9d941bb1a0b8a8a7f8f6ff to your computer and use it in GitHub Desktop.
CF Worker example: KV lookup and adding a customer header to a request
async function handleRequest(request) {
// Is the visitor in the VIP list?
let data = request.cf
let visitor_asn = data.asn
// Query the KV database
let network_name = await VIP_API_ASN.get(visitor_asn)
// Create the HTTP header value
let is_vip = (network_name !== null)
let msg = 'vip: ' + (is_vip ? 'yes' : 'no ') + '; ' + data.asn.toString().padStart(7) + ' - ' + data.asOrganization
console.log(msg);
// Clone the request so that it's no longer immutable
const newRequest = new Request(request);
// Add a custom header with the VIP message
newRequest.headers.append("x-vip", msg)
// Send the request on its way
let response = await fetch(newRequest);
// Return the response to the user
return response
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment