Skip to content

Instantly share code, notes, and snippets.

@nomadrat
Created December 3, 2022 15:20
Show Gist options
  • Save nomadrat/ca53704e99a8f718ec055b4360a2ba98 to your computer and use it in GitHub Desktop.
Save nomadrat/ca53704e99a8f718ec055b4360a2ba98 to your computer and use it in GitHub Desktop.
Geolocate the Location of an IP Address With Cloudflare Workers
/**
Read more at:
https://abstractkitchen.com/blog/geolocation-with-cloudflare-workers/
*/
addEventListener("fetch", event => {
const city = event.request.cf.city;
const country = event.request.cf.country;
const clientIP = event.request.headers.get("CF-Connecting-IP");
const clientInfo = JSON.stringify({
city: city,
country: country,
ip_addr: clientIP
}, null, 2);
const response = new Response(clientInfo, {
headers: {
"content-type": "application/json;charset=UTF-8"
}
});
const responseHeaders = new Headers(response.headers);
responseHeaders.set('Access-Control-Allow-Origin', '*');
return event.respondWith(
new Response(response.body, {
headers: responseHeaders,
status: response.status,
statusText: response.statusText
})
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment