Created
December 27, 2024 07:49
-
-
Save sontl/901e239bd46fa28b1bd709716c88dc7c to your computer and use it in GitHub Desktop.
Country detection using CF Worker
This file contains 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
addEventListener('fetch', event => { | |
event.respondWith(handleRequest(event.request)) | |
}) | |
async function handleRequest(request) { | |
const headers = { | |
'Access-Control-Allow-Origin': '*', | |
'Content-Type': 'application/json' | |
} | |
try { | |
// Get country directly from Cloudflare's request object | |
const countryCode = request.cf.country | |
const city = request.cf.city | |
const continent = request.cf.continent | |
return new Response(JSON.stringify({ | |
countryCode, | |
country: countryCode, // You might want to map this to full country name | |
city, | |
continent, | |
ip: request.headers.get('CF-Connecting-IP') | |
}), { headers }) | |
} catch (error) { | |
return new Response(JSON.stringify({ error: 'Failed to detect country' }), { | |
headers, | |
status: 500 | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment