Guessing user location with Cloudflare Workers

Recently I was building a landing page that needs some information relevant to user location displayed.

Using browser’s Geolocation API is obvious solution, but who whants to give precise geolocation to a random website on the internet. Also I belive only the fact of such ask will make customers uncomfortable.

Then I found a out that cloudflare has access to unprecise 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 matching ip’s with locations.


If you noticed a typo, or have a correction or question — write a comment to [email protected]