Created
December 3, 2022 15:20
-
-
Save nomadrat/ca53704e99a8f718ec055b4360a2ba98 to your computer and use it in GitHub Desktop.
Geolocate the Location of an IP Address With Cloudflare Workers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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