26 jan 2025
Guessing user location with Cloudflare Workers
Recently I was building a landing page that needed to display some information relevant to the user’s location.
Using the browser’s Geolocation API is an obvious solution, but who wants to give precise geolocation to a random website on the internet. Also, I believe that the mere fact of such a request will make customers uncomfortable.
Then I found out that Cloudflare has access to the imprecise location of any request going to the Cloudflare worker, and it’s accessible to read.
// this code lives in your cloudflare page worker function
// for example functions/api/location.ts
// which is your example.com/api/location
import type { PagesFunction } from '@cloudflare/workers-types';
export const onRequest: PagesFunction = async (context) => {
const { latitude, longitude, city, country } = context.request.cf || {};
const coordinates = {
latitude,
longitude,
city,
country,
};
return new Response(JSON.stringify(coordinates), {
headers: { 'Content-Type': 'application/json' },
});
};
If you are not using Cloudflare Workers, there are services that match IPs with locations.