Skip to content

Instantly share code, notes, and snippets.

@sontl
Created December 27, 2024 07:49
Show Gist options
  • Save sontl/901e239bd46fa28b1bd709716c88dc7c to your computer and use it in GitHub Desktop.
Save sontl/901e239bd46fa28b1bd709716c88dc7c to your computer and use it in GitHub Desktop.
Country detection using CF Worker
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